求助一个关于读入文件的问题
txt文本内容:3 10 2 5 9
运行结果:
3
10
0 0 0 2 5 9
存储的程序长度分别为:0 0 0 2 5
总共可以存储程序数:5
请按任意键继续. . .
为什么输出中会夹杂三个0?求解决方法
代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std;
//将字符串转换成整数
int StrToInt( const string &s )
{
return atoi(s.c_str());
}
int main()
{
//读取input.txt文件
ifstream input;
string word;
input.open("d:\\input.txt");
if(!input)
{
cout<<"无法打开input.txt! \n";
return 1;
}
input>>word;
vector <int> x(StrToInt(word));
cout<<StrToInt(word)<<endl;
input>>word;
int L=StrToInt(word);
cout<<L<<endl;
while(input>>word)
x.push_back(StrToInt(word));
for(int j=0;j<x.size();j++)
cout<<x[j]<<" ";
cout<<endl;
input.close();
int i=0,sum=0;
sort(x.begin(),x.end());//对给定的程序按照长度进行排//序
cout<<"存储的程序长度分别为:";
while(i<x.size()){
sum+=x[i];
if(sum<=L){
cout<<x[i]<<" ";//逐个输出存储的程序对应的长度
i++;
}
else{
cout<<endl;
cout<<"总共可以存储程序数:"<<i<<endl;//输出存//储的程序的总书目
break;
}
}
return 0;
}
[解决办法]
- C/C++ code
vector <int> x; x.push_back((StrToInt(word)));
