我正在尝试将包含整数的文本文件读入整数数组中。
如果输入为:1 3 4 5 6
(用空格隔开)它可以正常工作。
但是,如果输入为:1,3,4,5,6(逗号分隔), 它只打印1(第一个数字)。如果程序将1,3,4,5,6视为单个实体,则应该将1,3,4,5,6作为第一个索引打印出来吧? 还有File>>x这个表达式会检测其间隔并逐个取值吗?
但是,如果输入为:1,3,4,5,6(逗号分隔), 它只打印1(第一个数字)。如果程序将1,3,4,5,6视为单个实体,则应该将1,3,4,5,6作为第一个索引打印出来吧? 还有File>>x这个表达式会检测其间隔并逐个取值吗?
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int n = 0; //n is the number of the integers in the file ==> 12
int num;
int arr[100];
int x;
int sum = 0;
ifstream File;
File.open("integer.txt");
if(!File.is_open())
{
cout<<"It failed"<<endl;
return 0;
}
while(File>>x)
{
arr[n] = x;
n++;
}
File.close();
cout<<"n : "<<n<<endl;
for(int i=0;i<n;i++)
{
cout << arr[i] << " ";
}
return 0;
}
sscanf
是危险和类型不安全的。您还添加了另一个魔术数字数组char line [200]
,用混淆指针变量不必要地复杂化了代码,并使用了getline
成员函数,所有这些都是非常糟糕的编码风格。 - Christian Hackl