c++将文本文件读入整数和字符串

标签 c++ integer iostream

我有一个文本文件的标准读入,但我需要的是一行的前 3 个字符作为 int 读入,该行的其余部分作为字符串逐行读入。我已将示例文本放在下面的代码中。

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

int main () 
{
 char buffer[256];
 ifstream myfile ("example.txt");

  while (! myfile.eof() )
  {
    myfile.getline (buffer,100);
    cout << buffer << endl;
  }
  return 0;
}

最佳答案

大概是这样的(伪代码,相信你能看懂真正的操作!)

std::string line;
ifstream myfile ("example.txt");

// this gets a line of text from the file.
while(std::getline(myfile, line))
{
  // now you need to extract three characters and convert to int, so is it always guranteed?
  if (line.size() > 3)
  {
    std::string int_s = <substring from 0, size: 3>; // lookup this function in a reference!
    std::string rest_s = <substring from 3 to end>; // ditto for the lookup

    // now convert the integer part.
    long int int_v = <conversion routine, hint: strtol>; // lookup syntax in reference.
    // use...
  }
}

关于c++将文本文件读入整数和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6016353/

相关文章:

c++ - 给定一个源文件,有没有办法让 gcc 只返回直接包含的头文件列表?

java - 无法从 int 转换为 byte

c++ - 为什么 CFile + CArchive 比 C I/O 流性能更好?

c++ - Cmake 生成独立的makefile

c++ - 当类包含 boost::container::flat_set 时复制对象时出错

C++、ASM 和 cout

c++ - 用于读入字符串时 C++ 提取运算符的行为

java - 如何在java中执行整数的范围比较,例如.x>a<y

c++ - 在不更改数据类型的情况下可逆地组合两个 uint32_t

c++ - streambuf::xsgetn 和状态标志