[英]Reading formatted data from file in C++
我正在尝试编写代码以从文件读取数据。 该文件如下所示:
47012 "3101 E 7TH STREET, Parkersburg, WV 26101"
48964 "S16 W22650 W. LINCOLN AVE, Waukesha, WI 53186"
.
.
.
.
我需要将数字存储为整数,并将地址存储为字符串。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream myfile;
myfile.open("input.txt");
long int id;
string address;
myfile >> id;
cout << id << endl;
myfile >> address;
cout << address.c_str() << endl;
myfile.close();
system("pause");
return 0;
}
程序输出
47012
"3101
我需要的输出是
47012
3101 R 7TH STREET, Parkersburg, WV 26101
我该怎么做。 在此先感谢您的帮助
我会做类似以下的事情。 不,开个玩笑,我会在现实生活中使用Boost Spirit。 但是,这似乎也可以尝试使用标准库方法:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream myfile("input.txt");
std::string line;
while (std::getline(myfile, line))
{
std::istringstream linereader(line, std::ios::binary);
long int id;
linereader >> id;
if (!linereader)
throw "Expected number";
linereader.ignore(line.size(), '"');
string address;
if (!std::getline(linereader, address, '"'))
throw "Expected closing quotes";
cout << id << endl << address << endl;
}
myfile.close();
}
印刷:
47012
3101 E 7TH STREET, Parkersburg, WV 26101
48964
S16 W22650 W. LINCOLN AVE, Waukesha, WI 53186
只需使用getline
:
while (in >> id) {
if (!getline(in, address)) {
// (error)
break;
}
// substr from inside the quotes
addresses[id] = address.substr(1, address.length() - 2);
}
这不起作用,因为在尝试读取字符串时,流运算符>>
将空格作为定界符。
您可以使用getline(stream, address, '\\t');
读取具有特定定界符的字符串。
或者如果该行上没有其他要读取的内容,则只需简单地获取getline(stream, address)
即可:
long int id;
string address;
myfile >> id;
getline(stream, address);
这只是一个示例,请参见@ not-sehe的答案以获取完整的解决方案(使用getline
读取各行,然后使用stringstream
解析每一行)。
您可以使用cin.getline()来读取该行的其余部分。
首先读取数字,然后使用getline()读取剩余的所有内容。
>>
运算符在空格处终止一个字符串。我建议使用
char temp[100];
myfile.getline(temp,max_length);
这一次读取一行,然后您可以使用循环以所需的方式拆分行。
我想补充一点,您可能需要atoi(char *)
(来自cytpe.h
模块)函数将整数字符串转换为整数。
getline(myfile, address, '"');//dummy read skip first '"'
getline(myfile, address, '"');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.