C++ 如何从文件中读取数据,然后将数据转换为整数并将其存储在向量中
我试图从文本文件中读取数据,将其内容转换为整数,最后将整数值存储到向量中。但是,我遇到了一个问题,转换跳过了.txt文件中的最后一个数字,并且在打印向量时似乎在向量的开头添加了一个随机值 例如,我的test.txt文件具有以下值(注意:所有值都放在它自己的行上): 这是我的main.cpp:C++ 如何从文件中读取数据,然后将数据转换为整数并将其存储在向量中,c++,C++,我试图从文本文件中读取数据,将其内容转换为整数,最后将整数值存储到向量中。但是,我遇到了一个问题,转换跳过了.txt文件中的最后一个数字,并且在打印向量时似乎在向量的开头添加了一个随机值 例如,我的test.txt文件具有以下值(注意:所有值都放在它自己的行上): 这是我的main.cpp: #include <iostream> #include <fstream> #include <vector> using namespace std; int ma
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
vector<int> myIntArray;
string line;
ifstream fileName("test.txt");
for(int number; getline(fileName, line, '\n'); number = stoi(line))
{
myIntArray.push_back(number);
cout << "Reading in number from the file: " << number << endl;
}
}
我不确定第一个数字(28156)是从哪里来的,也不知道为什么它跳过了我的test.txt文件中的最后一个数字(4),但这就是我的代码存在的问题。在执行循环体之后执行
循环的的第三部分(number=stoi(line)
)
因此,28156
是未初始化的非静态局部变量的不确定值,最后一个4
被转换并丢弃
您必须在使用number
之前执行转换,如下所示:
for(int number; getline(fileName, line, '\n'); )
{
number = stoi(line);
myIntArray.push_back(number);
cout << "Reading in number from the file: " << number << endl;
}
for(int number; filename >> number;)
{
myIntArray.push_back(number);
cout << "Reading in number from the file: " << number << endl;
}
for(int-number;getline(文件名,行,'\n');)
{
编号=stoi(线);
myIntArray.推回(数字);
cout您可以这样简化循环:
for(int number; getline(fileName, line, '\n'); )
{
number = stoi(line);
myIntArray.push_back(number);
cout << "Reading in number from the file: " << number << endl;
}
for(int number; filename >> number;)
{
myIntArray.push_back(number);
cout << "Reading in number from the file: " << number << endl;
}
for(int-number;filename>>number;)
{
myIntArray.推回(数字);
cout您还可以使用输入迭代器构造向量:
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
using namespace std;
ifstream f("test.txt");
vector<int> myIntArray(istream_iterator<int>(f), {});
for(auto i: myIntArray) {
cout << "Reading in number from the file: " << i << endl;
}
}
#包括
#包括
#包括
#包括
int main(){
使用名称空间std;
iff流(“test.txt”);
向量myIntArray(istream_迭代器(f),{});
用于(自动i:myIntArray){
cout number在第一次迭代时未初始化。请记住,(a;b;c)d
的相当于{a;而(b){d;c}}
,然后考虑变量初始化。很好,我总是忘记文件流操作符。