c++ - 我想从一个有空格的文件中读取 C++ ifstream

标签 c++ io ifstream

我的文件是这样的

0 0 5
1 10 20
2 10 10
3 15 3
4 20 30
5 25 5

我将它保存在一个 vector 中。我不确定如何阅读它以便我可以将每个组件保存在不同的 vector 中。

尝试解决方案:

if (inFile.is_open()) { 
     while ( inFile) { 
          getline (inFile,line); 
          cout << line << endl; 
     } 
     inFile.close(); 
}

最佳答案

我想这就是你想要做的:

ifstream fin("C:/file.txt");

if(!fin)
{
    cout<<"Cannot Open File";
    exit(EXIT_FAILURE);
}

vector<vector<int>> v;

int vector_length = 3;

int count = 0;
while(!fin.eof()) //Read till the end of file
{       
    v.push_back(vector<int>()); //Add vector for new line
    int number;
    for(int i=0; i<vector_length; i++)
    {
        fin>>number;  //Read a number from the file
        v[count].push_back(number);  //Add the number to the vector
    }
    count++;
}


//Show the output to confirm that the file has been read correctly
for(int i=0; i<v.size(); i++)
{
    for(int j=0; j<v[i].size(); j++)
    {
        cout<<v[i][j]<<"\t";
    }
    cout<<endl;

}

关于c++ - 我想从一个有空格的文件中读取 C++ ifstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791754/

相关文章:

c++ - 从主框架窗口标题中删除 "Untitled - "

java - 我可以多路分解流吗?

file - 如何从 Julia 中打开的 IOStream 中检索文件路径

c++ - 将文件读入缓冲区

java - 游戏编程

C++,通过引用传递堆栈上的二维数组以运行

c++ - 库的字符串编码应该符合 Unicode 还是灵活的?

java - FileWriter 没有写入我的所有数据

c++ - std::ifstream 读取大数的错误大小

c++ - 如何在 C++ boost ublas 中将文件流式传输到矩阵中?