从 C++ 中的文件中读取整数和字符的混合;
我在用 C++ 读取文件时遇到一些问题。我只能读取整数或字母。但我无法同时读取两者,例如 10af、ff5a。我的过程如下:
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cerr << "You should provide a file name." << std::endl;
return -1;
}
std::ifstream input_file(argv[1]);
if (!input_file) {
std::cerr << "I can't read " << argv[1] << "." << std::endl;
return -1;
}
std::string line;
for (int line_no = 1; std::getline(input_file, line); ++line_no) {
//std::cout << line << std::endl;
-----------
}
return 0;
}
所以我想做的是,我允许用户指定他想要读取的输入文件,并且我使用 getline 来获取每一行。我可以使用标记方法来仅读取整数或仅读取字母。但我无法同时阅读两者。如果我的输入文件是
2 1 89ab
8 2 16ff
读取此文件的最佳方法是什么?
预先非常感谢您的帮助!
I have some trouble with reading of a file in C++. I am able to read only integers or only alphabets. But I am not able to read both for example, 10af, ff5a. My procedure is as follows:
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cerr << "You should provide a file name." << std::endl;
return -1;
}
std::ifstream input_file(argv[1]);
if (!input_file) {
std::cerr << "I can't read " << argv[1] << "." << std::endl;
return -1;
}
std::string line;
for (int line_no = 1; std::getline(input_file, line); ++line_no) {
//std::cout << line << std::endl;
-----------
}
return 0;
}
So what I am trying to do is, I am allowing the user to specify the input file he wants to read, and I am using getline to obtain each line. I can use the method of tokens to read only integers or only alphabets. But I am not able to read a mix of both. If my input file is
2 1 89ab
8 2 16ff
What is the best way to read this file?
Thanks a lot in advance for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会使用
std::stringstream
,并且从 89ab 和 16ff 开始使用std::hex
看起来像十六进制数字。应如下所示:
您需要
#include
I'd use a
std::stringstream
, and usestd::hex
since 89ab and 16ff look like hex numbers.Should look like this:
You will need to
#include <sstream>
使用
您可以读取
std::string
类型的输入,它可以是数字和字母的任意组合。您不一定需要逐行读取输入,然后尝试解析它。>>
运算符将空格和换行符视为分隔符。Using
you can read inputs of type
std::string
which could be any combination of digits and alphabets. You don't necessarily need to read input line by line and then try to parse it.>>
operator considers both space and newline as delimiters.