C++ 如何在C++中将文件读入向量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15138785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:04:35  来源:igfitidea点击:

How to read a file into vector in C++?

c++vectorfile-io

提问by Orgmo

I need to read from a .dataor .txtfile containing a new floatnumber on each line into a vector.

我需要从每行包含一个新数字的.data.txt文件读取float到一个向量中。

I have searched far and wide and applied numerous different methods but every time I get the same result, of a Main.size()of 0and an error saying "Vector Subscript out of Range", so evidently the vector is just not reading anything into the file.

我已经进行了广泛的搜索并应用了许多不同的方法,但是每次我得到相同的结果时,都会出现 a Main.size()of0和错误提示"Vector Subscript out of Range",因此很明显,向量只是没有将任何内容读入文件。

Note: the file is both in the folder and also included in the VS project.

注意:该文件既在文件夹中,也包含在 VS 项目中。

Anyway, here's my code:

无论如何,这是我的代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>

using namespace std;

int main() {

    vector<double> Main;
    int count;
    string lineData;
    double tmp;

    ifstream myfile ("test.data", ios::in);

    double number;  

    myfile >> count;
    for(int i = 0; i < count; i++) {
        myfile >> tmp;
        Main.push_back(tmp);
        cout << count;
    }

    cout << "Numbers:\n";
    cout << Main.size();
    for (int i=0; i=((Main.size())-1); i++) {
        cout << Main[i] << '\n';
    }

    cin.get(); 
    return 0;
}

The result I get is always simply:

我得到的结果总是很简单:

Numbers:
0

回答by juanchopanza

Your loop is wrong:

你的循环是错误的:

for (int i=0; i=((Main.size())-1); i++) {

Try this:

尝试这个:

for (int i=0; i < Main.size(); i++) {

Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:

此外,将数字读入向量并将它们写入标准输出的更惯用的方法是:

#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm> // for std::copy

int main()
{
  std::ifstream is("numbers.txt");
  std::istream_iterator<double> start(is), end;
  std::vector<double> numbers(start, end);
  std::cout << "Read " << numbers.size() << " numbers" << std::endl;

  // print the numbers to stdout
  std::cout << "numbers read in:\n";
  std::copy(numbers.begin(), numbers.end(), 
            std::ostream_iterator<double>(std::cout, " "));
  std::cout << std::endl;

}

although you should check the status of the ifstreamfor read errors.

尽管您应该检查ifstream读取错误的状态。

回答by Mike DeSimone

Just to expand on juanchopanza's answer a bit...

只是为了扩展 juanchopanza 的答案......

for (int i=0; i=((Main.size())-1); i++) {
    cout << Main[i] << '\n';
}

does this:

做这个:

  1. Create iand set it to 0.
  2. Set ito Main.size() - 1. Since Mainis empty, Main.size()is 0, and igets set to -1.
  3. Main[-1]is an out-of-bounds access. Kaboom.
  1. 创建i并将其设置为0.
  2. 设置iMain.size() - 1。由于Main是空的,Main.size()0,并且i被设置为-1
  3. Main[-1]是越界访问。卡布姆。

回答by phoeagon

Just a piece of advice. Instead of writing

只是一个建议。而不是写作

for (int i=0; i=((Main.size())-1); i++) {
   cout << Main[i] << '\n';
}

as suggested above, write a:

按照上面的建议,写一个:

for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
   cout << *it << '\n';
}

to use iterators. If you have C++11support, you can declare ias auto i=Main.begin()(just a handy shortcut though)

使用迭代器。如果你有C++11支持,你可以声明iauto i=Main.begin()(虽然只是一个方便的快捷方式)

This avoids the nasty one-position-out-of-bounderror caused by leaving out a -1unintentionally.

这避免了由于无意中遗漏了一个令人讨厌的单位置越界错误-1

回答by Shriraj

1. In the loop you are assigning value rather than comparing value so

1. 在循环中,您正在分配值而不是比较值,因此

i=((Main.size())-1) -> i=(-1) since Main.size()

i=((Main.size())-1) -> i=(-1) 因为 Main.size()

Main[i] will yield "Vector Subscript out of Range" coz i = -1.

Main[i] 将产生“向量下标超出范围”,因为 i = -1。

2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.

2. 你得到 Main.size() 为 0 可能是因为它找不到文件。给出文件路径并检查输出。初始化变量也很好。

回答by muhammadOsama

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
fstream dataFile;
string name , word , new_word;
vector<string> test;
char fileName[80];
cout<<"Please enter the file name : ";
cin >> fileName;
dataFile.open(fileName);
if(dataFile.fail())
{
     cout<<"File can not open.\n";
     return 0;
}
cout<<"File opened.\n";
cout<<"Please enter the word : ";
cin>>word;
cout<<"Please enter the new word : ";
cin >> new_word;
while (!dataFile.fail() && !dataFile.eof())
{
      dataFile >> name;
      test.push_back(name);
}
dataFile.close();

}

回答by muhammadOsama

  //file name must be of the form filename.yourfileExtension
       std::vector<std::string> source;
bool getFileContent(std::string & fileName)
{
    if (fileName.substr(fileName.find_last_of(".") + 1) =="yourfileExtension")
    {

        // Open the File
        std::ifstream in(fileName.c_str());

        // Check if object is valid
        if (!in)
        {
            std::cerr << "Cannot open the File : " << fileName << std::endl;
            return false;
        }
        std::string str;
        // Read the next line from File untill it reaches the end.
        while (std::getline(in, str))
        {
            // Line contains string of length > 0 then save it in vector
            if (str.size() > 0)
                source.push_back(str);
        }
        /*for (size_t i = 0; i < source.size(); i++)
    {
        lexer(source[i], i);
        cout << source[i] << endl;
    }
    */
        //Close The File
        in.close();
        return true;
    }
    else
    {
        std::cerr << ":VIP doe\'s not support this file type" << std::endl;
        std::cerr << "supported extensions is filename.yourfileExtension" << endl;
    }
}