I have a file called file.txt and it has this structure:
owner_name : first_last_name
filesize : 1000
is_legal_file : yes
date : someDate
.
.
.
I want to get the value in fileSize. (1000 in this example.)
How do I get this information?
Another easy way aside from strtok is to do a while (infile >> myString)
. Just figure out the number of the value you want and take it out.
std::string myString;
ifstream infile("yourFile.txt");
while (infile >> myString)
{
//Do an if-statement to only select the value you want.
//Leaving this for you since I think it's homework
}
sstream
#include <iostream>
#include <sstream>
#include <string>
int main() {
using namespace std;
for (string line; getline(cin, line); ) {
istringstream ss(line);
string name;
ss >> name; // assume spaces between all elements in the line
if (name == "filesize") {
string sep;
int filesize = -1;
ss >> sep >> filesize;
if (sep == ":" && ss) {
cout << filesize << endl;
break;
}
}
}
}
1000
Related: Split a string in C++?
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.