【问题标题】:Reading and storing integers in a file在文件中读取和存储整数
【发布时间】:2013-12-21 23:51:05
【问题描述】:

我有一个 file.txt 例如:

15 25 32 // exactly 3 integers in the first line. 
string1
string2
string3
*
*
*
*

我想要做的是,读取 15,25,32 并将它们存储到让我们说 int a,b,c;

有人帮我吗?提前致谢。

【问题讨论】:

    标签: c++ io fstream


    【解决方案1】:

    标准习语使用 iostreams:

    #include <fstream>
    #include <sstream>
    #include <string>
    
    std::ifstream infile("thefile.txt");
    
    std::string first_line;
    
    if (!infile || !std::getline(first_line, infile)) { /* bad file, die */ }
    
    std::istringstream iss(first_line);
    int a, b, c;
    
    if (!(iss >> a >> b >> c >> std::ws) || iss.get() != EOF)
    { 
        // bad first line, die
    }
    
    // use a, b, c
    

    【讨论】:

      【解决方案2】:

      您可以使用std::ifstream 来读取文件内容:

      #include <fstream>
      std::ifstream infile("filename.txt");
      

      然后您可以使用std::getline() 读取带有数字的行:

      #include <sstream>
      #include <string>
      std::string line;
      std::getline(infile, line);
      

      然后,您可以使用std::istringstream 来解析存储在该行中的整数:

      std::istringstream iss(line);
      int a;
      int b;
      int c;
      
      iss >> a >> b >> c;
      

      【讨论】:

      • 不客气。请注意,@KerrekSB 的回答也显示了错误检测。
      • @Mr.C64:是的,如果提取失败,访问abc 可能是未定义的行为。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      相关资源
      最近更新 更多