我真的很简单。我已经打开一个文本文件,并且希望它读取getline的第一行。我希望它接受该行中的所有整数,并用逗号分隔,并将它们加在一起以存储在变量中。但是,我不太确定如何使用定界符进行设置。
#include <fstream>
#include <iostream>
int main(){
std::fstream codeBreaker;
int x,y,z;
codeBreaker.open("input.txt");
void decipher();
void encode();
std::cout << "Have a nice day!" << std::endl;
return 0;
}
void decipher(){
}
void encode(){
}
您已经概述了第一步:用std::getline
读第一行。但您遗漏的一点是,几乎在任何时候读取数据都想检查读取是否成功。
std::string line;
if (std::getline(infile, line))
// we got some data
else
// the read failed
从那里,您需要将该行解析为单个数字。一种方法是使用stringstream
。
std::stringstream buffer(line);
由于您的数字用逗号分隔,因此,您需要先阅读(但忽略)逗号,然后阅读下一个数字。继续直到到达行尾为止,通常可以通过检查读取数字是否成功来找到。
int number;
while (buffer >> number) {
char ch;
buffer.get(ch);
if (ch != ',')
// unexpected input ?
// do something with the number we just read here
}