从文件中读取数字

时间:2012-07-31 01:17:58

标签: c++ string file ifstream

我有一个包含许多数字的文件。该文件看起来像“192 158 100 0 20 200”,基本上就是这样。如何一次加载文件编号值1并在C ++中以屏幕显示?

5 个答案:

答案 0 :(得分:4)

尝试这样的事情:

int val;
std::ifstream file("file");
while (file >> val)        
    std::cout << val;

答案 1 :(得分:3)

以下程序应打印每个数字,每行一个:

#include <iostream>
#include <fstream>

int main (int argc, char *argv[]) {
    std::ifstream ifs(argv[1]);
    int number;

    while (ifs >> number) {
       std::cout << number << std::endl;
    }
}

答案 2 :(得分:1)

请考虑以下代码:

    ifstream myReadFile;
    myReadFile.open("text.txt");
    int output;
    if (myReadFile.is_open())
    {
        while (fs >> output) {   
            cout<<output;
        }
    }

//Of course closing the file at the end.
myReadFile.close();

同样,在使用上面的示例时,请在代码中包含iostream和fstream。

请注意,您需要开始打开文件流进行读取,您可以尝试通过char读取它,并检测它之间是否有任何空白。

祝你好运。

答案 3 :(得分:1)

#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

int main() {
    std::ifstream fs("yourfile.txt");
    if (!fs.is_open()) {
        return -1;
    }

    // collect values
    // std::vector<int> values;
    // while (!fs.eof()) {
    //    int v;
    //    fs >> v;
    //    values.push_back(v);
    // }
    int v;
    std::vector<int> values;
    while (fs >> v) {
        values.push_back(v);
    }
    fs.close();    

    // print it
    std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));

    return 0;
}

答案 4 :(得分:1)

另一种方法:

std::string filename = "yourfilename";

//If I remember well, in C++11 you don't need the
//conversion to C-style (char[]) string.
std::ifstream ifs( filename.c_str() );


//Can be replaced by ifs.good(). See below.
if( ifs ) {
    int value;

    //Read first before the loop so the value isn't processed
    //without being initialized if the file is empty.
    ifs >> value;

    //Can be replaced by while( ifs) but it's not obvious to everyone
    //that an std::istream is implicitly cast to a boolean.
    while( ifs.good() ) { 
        std::cout << value << std::endl;
        ifs >> value;       
    }
    ifs.close();
} else {
    //The file couldn't be opened.
}

错误处理可以通过多种方式完成。