【问题标题】:Read files by character C++按字符 C++ 读取文件
【发布时间】:2012-03-03 17:29:58
【问题描述】:

我想读取一个带有数字的文件 例如:

2
2 3 
2 3 4 
5 6 7

3 
2 2
1 2 
2 3 

我使用了 getline () 函数并将结果存储在一个向量(字符串)中。但是,当我访问向量中的元素时,会存储带有空格的整行。我想按数字存储元素(数字代表一个矩阵)

【问题讨论】:

标签: c++ file vector matrix


【解决方案1】:
#include<fstream>
#include<iterator>
#include<vector>

int main(int, char*[])
{
    std::ifstream file("numbers.txt");
    std::vector<int> data((std::istream_iterator<int>(file)),
                          std::istream_iterator<int>());
}

会给你一个整数向量。

【讨论】:

    【解决方案2】:

    您可以只使用stream::operator &gt;&gt;

    int x;
    cin >> x;
    

    或使用文件流:

    #include <fstream>
    
    int main()
    {
        std::ifstream f("input.txt");
        int x;
        f >> x;
        std::cout << x;
        return 0;
    }
    

    【讨论】:

    • 如何使用 cin 读取文件?我不需要以某种方式链接 cin 来读取文件吗?
    • @Josh, cin 只是一个例子。 cin 是一个流,您可以使用另一个流而不是cin
    猜你喜欢
    • 2016-08-03
    • 2012-01-24
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 2011-06-16
    • 2014-01-21
    • 2012-02-04
    • 2017-09-06
    相关资源
    最近更新 更多