C++ 如何通过跳过=,从txt文件中读取整数?
我有如上所述的txt文件。如果没有=,如何从该文件中只读整数?以下是基本框架:逐行读取和解析C++ 如何通过跳过=,从txt文件中读取整数?,c++,file-io,integer,string-parsing,C++,File Io,Integer,String Parsing,我有如上所述的txt文件。如果没有=,如何从该文件中只读整数?以下是基本框架:逐行读取和解析 1 = 0 0 97 218 2 = 588 0 97 218 3 = 196 438 97 218 4 = 0 657 97 218 5 = 294 438 97 218 for(std::string-line;std::getline(std::cin,line);) { 标准::istringstream iss(线); int n; 字符c; 如果(!(iss>>n>>c)| | c!='=
1 = 0 0 97 218
2 = 588 0 97 218
3 = 196 438 97 218
4 = 0 657 97 218
5 = 294 438 97 218
for(std::string-line;std::getline(std::cin,line);)
{
标准::istringstream iss(线);
int n;
字符c;
如果(!(iss>>n>>c)| | c!='='=')
{
//分析错误,正在跳行
继续;
}
对于(int i;iss>>i;)
{
std::cout另一种可能性是将=
分类为空白的方面:
for (std::string line; std::getline(std::cin, line); )
{
std::istringstream iss(line);
int n;
char c;
if (!(iss >> n >> c) || c != '=')
{
// parsing error, skipping line
continue;
}
for (int i; iss >> i; )
{
std::cout << n << " = " << i << std::endl; // or whatever;
}
}
当然,把所有的数字加起来可能不是很明智,因为每一行的第一个数字似乎是一个行号——这只是一个快速演示,表明我们在阅读数字时没有额外的“东西”造成任何问题。@NominSim我用ifstream创建了一个循环,但当它read=出现问题时,我无法理解。@droidmachine:显示您的代码。没有代码很难判断,但如果您使用“=”的话,问题很可能是因为没有首先检查输入是否为整数作为一个整数,你会得到不理想的结果。他没有做出任何努力。不妨将该网站重命名为writemycodeforme.com
class my_ctype : public std::ctype<char>
{
mask my_table[table_size];
public:
my_ctype(size_t refs = 0)
: std::ctype<char>(&my_table[0], false, refs)
{
std::copy_n(classic_table(), table_size, my_table);
my_table['='] = (mask)space;
}
};
int main() {
std::istringstream input(
"1 = 0 0 97 218\n"
"2 = 588 0 97 218\n"
"3 = 196 438 97 218\n"
"4 = 0 657 97 218\n"
"5 = 294 438 97 218\n"
);
std::locale x(std::locale::classic(), new my_ctype);
input.imbue(x);
std::vector<int> numbers((std::istream_iterator<int>(input)),
std::istream_iterator<int>());
std::cout << "the numbers add up to: "
<< std::accumulate(numbers.begin(), numbers.end(), 0)
<< "\n";
return 0;
}