gpt4 book ai didi

c++ - 计算文件 C++ 中每一行中的整数数量

转载 作者:搜寻专家 更新时间:2023-10-31 02:18:24 26 4
gpt4 key购买 nike

我的任务是用 C++ 计算一个 txt 文件中每一行的整数数量。

文件格式为:

    Steve Road_43 St43 32 45 2 5 7 23 545

John Road_21 Dt_4 3 4 5 12 31 0

最后的格式是 问题是每一行的整数个数不同,那么我怎么知道每一行的整数个数呢?

我的代码->

#include <iostream>
#include <fstream>
#include <sstream>
#include <ctype.h>
#include <string>


using namespace std ;




int main()
{

string File_Name ,
temp ;



int counter_0 = 0 ;



cout << " Please enter the File-Name : " ;
getline ( cin, File_Name ) ;
cout << endl << endl << endl ;


ifstream FP_1 ( File_Name ) ;


if ( FP_1.is_open( ) )
{

while ( ! FP_1.eof( ) )
{

getline ( FP_1, temp ) ;
cout << temp;
stringstream str ( temp ) ;

int x ;

while ( str >> x )
{
counter_0 ++ ;
}

cout << " " << counter_0 <<endl;
counter_0 = 0;

}

}
else
{
exit ( 1 ) ;
}


FP_1.close ( ) ;



system ( " pause " ) ;
}

counter_0 始终为零..不计算整数

最佳答案

只要 str >> x 在输入中看到非 int 类型,str 的状态就会设置为 fail 并且您永远不会恢复它。

因此不会读取任何数字,因为这些行以非数字值开头。

您可以预先使用两个非 int 值,然后读取所有 int 值:

     int x ;
std::string dummy;

str >> dummy >> dummy;

while ( str >> x )
{
counter_0 ++ ;
}

关于c++ - 计算文件 C++ 中每一行中的整数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34545043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com