我需要将字符串解析为具有不同数据类型(整数,字符串)的变量。C++将字符串解析为不同的数据类型变量
问题中的字符串是从文件中的一行中获取的。
我想知道是否有类似于inFile >> var1 >> var2 >> etc的函数;我可以使用字符串。以下是文件的完整行。
2016年12月6日的“政府和大企业之间的乱伦关系在黑暗中繁盛。〜杰克·安德森[4]” 0 3 39蓝白PATRICK巴德韦尔[email protected]
我已经分配了“2016/12/6”,“s”以及引号和变量之间的所有使用inFile >>;的内容。另外,在双引号的最后出现后,我将所有内容都存储在字符串restOfLine中。现在,我想将restOfLine解析为每个值的变量(0,3,39,blue,white,Patrick,Bardwell,[email protected]都应该是单独的变量)。有没有像inFile这样的方法可以用来做到这一点?我还尝试将它们与restOfline.find()和restOfLine.substr()分开,但一直未能弄清楚。同样,如果我可以比我当前的代码更有效地将整个行中的每个值分开,我宁愿那样做。下面的当前代码。任何帮助深表感谢。
int main()
{
// Declare variables
string userFile;
string line;
string date;
char printMethod;
string message;
int numMedium;
int numLarge;
int numXL;
string shirtColor;
string inkColor;
string firstName;
string lastName;
string customerEmail;
string firstLine;
string restOfLine;
// Prompt user to 'upload' file
cout << "Please input the name of your file:\n";
cin >> userFile;
fstream inFile;
inFile.open(userFile.c_str());
// Check if file open successful -- if so, process
if (inFile.is_open())
{
getline(inFile, firstLine); // get column headings out of the way
cout << firstLine << endl << endl;
while(inFile.good())
// while we are not at the end of the file, process
{
getline(inFile, line);
inFile >> date >> printMethod; // assigns first two values of line to date and printMethod, respectively
int pos1 = line.find("\"");
// find first occurrence of a double quotation mark and assign position value to pos1
int pos2 = line.rfind("\"");
// find last occurrence of a double quotation mark and assign position value to pos2
string message = line.substr(pos1, (pos2 - pos1));
// sets message to string between quotation marks
string restOfLine = line.substr(pos2 + 2);
// restOfLine = everything after the message -- used to parse
}
inFile.close();
}
// If file open failure, output error message, exit with return 0;
else
{
cout << "Error opening file";
}
return 0;
}
您是否已经知道[stringstream](http://stackoverflow.com/questions/20594520/what-exactly-does-stringstream-do)? –