计算文件C++中每行的整数数量
Count the amount of integers in every line from file C++
我的任务是计算C++中txt文件中每行的整数数量。
文件格式为:
Steve Road_43 St43 32 45 2 5 7 23 545
John Road_21 Dt_4 3 4 5 12 31 0
最后,格式是<字符串字符串int int int int…..int>问题是每行中的整数数量不同,那么我如何知道每行中整数的数量呢?
我的代码->
#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 ++ ;
}
相关文章:
- 如何初始化整数+字符串数组
- 整数指针数组的元素是否可以指向整数数组?
- 整数指针数组的大小
- 将整数输入数组的方法比 scanf() 或 cin 更快?
- 将字符 2d 数组转换为整数 2d 数组
- 取消随机排列整数/字符数组
- 用于存储原子整数的数组
- 在 C++ 中使用 10 个随机整数的数组进行气泡排序不起作用
- 指向整数 C++ 数组的指针
- 从矢量<对<双*,对<双*,整数*>>到数组的可视化C++转换
- 设置整数等于数组中的值数量
- 计算每个连续的整数在数组中总和
- 从文件中读取整数到数组
- 创建字符指针和整数指针数组
- 使用 const 整数声明数组
- 创建整数 2d 数组(与字符串 2d 数组相比),而不提及维度
- 发送 2 个整数的数组作为参数
- 如何在向量内的结构内打印指向整数的数组
- C++:使用 STL 排序对不同列上的整数 2d 数组进行排序的时间复杂度
- 对1000个整数的数组进行排序