【发布时间】: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;
有人帮我吗?提前致谢。
【问题讨论】:
我有一个 file.txt 例如:
15 25 32 // exactly 3 integers in the first line.
string1
string2
string3
*
*
*
*
我想要做的是,读取 15,25,32 并将它们存储到让我们说 int a,b,c;
有人帮我吗?提前致谢。
【问题讨论】:
标准习语使用 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
【讨论】:
您可以使用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;
【讨论】:
a、b 或c 可能是未定义的行为。