-
February 16th, 2012, 10:58 PM
#1
[RESOLVED] File I/O and String question
i have a text file called example.txt and it contains the following lines.
21 squarepants,Spongebob
115 barack,Obama
7 Carter,Mc Farland
227 Abraham Carter,Lincoln
Basically, I have to read into this file, take the last name and capitalize it. I need to have the capitalized last name outputed onto another text file, which i called outfile.
I just started c++ and the class is basically self-teaching. I am not an expert, but i do have 2 approaches to this program. I just need help writing the code.
My first approach is if i can use a substring and take out the string between the first space and the comma. I tried it but when compiling it never seems to work. I feel it has something to do with my syntax. Another possible approach could be if i can clear all the numbers and get the postion of the comma and clear everything after the comma. That way all i have left is a string with just the last name. Well, below is what I have so far. I have included both of my approaches, so someone can correct my code.
Thank You in advance for your help. I would really appreciate it!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line, str, str1;
ifstream infile; //object for reading from a file
ofstream outfile; // object for writing to a file
size_t pos;
infile.open ("example.txt", ios::app); //open a file for writing
outfile.open ("results.txt");
if (infile.is_open()) // if file was able to open
{
while (!infile.eof())
cout << (char) infile.get();
getline(infile,line); //print out the lines in the entire file
str1 = line;
//Approach #1
pos = str.find(" "); // position of " " in str
pos = str.find(","); // position of "," in str
str1 = str.substr (" ", ","); // get the string between the first
space and the comma
// Approach #2
pos = str.find(" "); // position of " " in str
pos = str.find(","); // position of "," in str
str2 = str.substr (pos); // get everything after the comma
str2.erase(pos); // erase everything after the comma. Is this line
even correct?
str1=last;
cout << uppercase << last << endl;
outfile << last << endl;
infile.close();
outfile.close();
}
else
{
cout << "Error opening file";
}
return 0;
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|