在文件中读取和存储整数

时间:2013-12-21 23:51:06

标签: c++ io fstream

我有一个file.txt,例如:

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

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

有人帮我吗?提前谢谢。

2 个答案:

答案 0 :(得分:2)

标准习语使用iostream:

#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

答案 1 :(得分:1)

您可以使用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;
相关问题