Say that I want to read in a .txt file and is formatted in such a way
Max,1979
Wade,1935
Hugh,1983
Eric,1936
Here is the code I am using to
Store it into a vector of string and int (For names and years respectively)
void calcAges(){ while (getline(infile, line, ',')){ names.push_back(line); years.push_back(line); } } void printNames(){ cout << "\\n\\tDisplaying data...\\n"; for (int i = 0; i < counter; i++){ cout << (i + 1) << ".\\tName: " << names[i] << "\\tYear: " << years[i] << endl; } }
Output should look like:
1. Name: Max Year: 1979
.
.
.
and so on...
However, I'm having trouble trying to make it so the file I read into my "infile" split at both a comma and a new line. I am storing these variables into a vector array so I can sort and switch later on. I am stumped at this point.
The new line is considered as a normal character once you have given ',' as delimiter. So use getline()
without specifying a delimiter (default is new line) and try to extract the name and year from the string you have obtained. It can be done pretty easily using find_first_of()
and substr()
Example:
while(getline(infile,str))
{
int index = str.find_first_of(',');
string name = str.substr(0,index);
string date = str.substr(index+1);
// Do something with name and date
}
A StringStream is much more powerful when it comes to these kind of operations. However, in your case (which is considered rather simple) you can get away with simple operations on strings. I would suggest reading each line into your temp string then split it on the comma and add the values into your vectors, something like the following:
void calcAges(){
while (getline(infile, line)){ // Read a whole line (until it reads a '\n', by default)
names.push_back(line.substr(0,line.find(",")); // Read from the beginning of the string to the comma, then push it into the vector
years.push_back(std::stoi(line.substr(line.find(",") + 1)); // Read from the comma to the end of the string, parse it into an integer, then push it into the vector
}
}
I'm assuming that you're using std::string
from the <string>
library as the type for your line
variable.
I didn't compile and test this by the way, so I'm not sure it would work as is, but I wrote it just to give you an idea about the logical approach
Cheers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.