如何从文件中读取字符和整数
how to read characters and integers from a file?
所以我有一个看起来像这样的数据文件:
x+y+z
30 45 50
10 20 30
我只需要运算符,所以"+"+"我能够使用file.get()
成功地获取这些字符并将它们放入数组中。问题是我需要得到下一行数字,并将它们赋值为x,yz。我知道我不能使用.get(),我必须使用getline
。我是否也必须取消file.get()
并使用getline
作为第一部分?
我看了一下这里发布的一些问题,但没有一个像我的问题注意,我实际上将在程序的另一部分使用这些值,只是使用cout
来查看我的值是否被正确读取这是我以前的代码:
main(int argc, char *argv[])
{
int a=0;
int n;
fstream datafile;
char ch;
pid_t pid;
int a, b, c, result;
string line;
datafile.open("data1.txt");
if(datafile)
{
for(int i=0; i <9; i++)
{
datafile.get(ch);
if (ch == '*'||ch == '/'||ch == '+'||ch == '-')
{
operations[a] = ch;
cout<<operations[a];
a++;
}
}
}
else
cout<<"Error reading file";
}
这就是我一开始获取文件第一行的方式。它按照我的意愿工作,可能不是最好的编码,但它工作了。尽管如此,我还是试图获得文件的其余部分,这次是使用getline
,但我得到的不是数字,而是一堆随机的胡言乱语/数字。我知道如果我使用getline
,第一行就不能在我的循环中。我知道这就是我得到数字的方法。
while(getline(datafile, line))
{
istringstream ss(line);
ss >> x >> y >> z;
cout<<x<<""<<y<<""<<z;
}
以下内容对第一行有意义吗,或者我遗漏了什么:
string input;
std::getline(datafile, input)
for (int i = 0; i < input.size(); i++)
if (input[i] == '+' || ...)
{
operations[a] = input[i];
a++;
}
如果你不想使用getline,你可以简单地读取整个文件流(注意,bool是一种相当天真的处理问题的方法,我建议在你的实际代码中使用更优雅的方法):
bool first = true;
string nums;
int lines = 0;
vector<vector<int>> numlines;
vector<int> topush;
while (!datafile.eof())
{
char ch = datafile.get()
if (ch == 12 && first) //I don't know if 'n' is valid, I'd assume it is but here's the sure bet
first = false;
else if (first && (ch == '+' || ...))
{
operator[a] = ch;
a++;
}
else if (!first && (ch >= '0' && ch <= '9'))
{
if (!(datafile.peek() >= '0' && datafile.peek() <= '0'))
{
numlines[lines].push_back(atoi(nums.c_str());
nums.clear();
if (datafile.peek() == 12)
{
numlines.push_back(topush);
lines++;
}
}
else
nums = nums + ch;
}
老实说,我不能确定以上内容是否正确,我建议您修改代码,只使用getline。你需要添加#include才能获得atoi。
将其添加到您的代码中:
while(!datafile.eof()){
string s;
getline(datafile, s);
istringstream in(s);
string tmp;
while(in >> tmp){
int i = stoi(tmp)
//Do something with i....
}
}
相关文章:
- 显示基于用户输入的整数的字符
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 将超出范围的整数分配给有符号字符类型
- 碱基对映射 - 将 argv[i] 移动到整数或字符作为输入
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 输入验证以筛选出字符、字符串和一系列整数
- 字符和整数中 **(ptr+1) 的值差异
- 如何将整数向量值插入字符向量
- 字符到整数数组
- 为什么对无符号字符进行算术运算会将它们提升为有符号整数
- 不能将字符转换为整数吗?
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- 为什么我们不能将使用异或运算找到的整数转换为字符?
- 有没有办法将字符类型转换为整数?
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- (C/C++)fscanf_s从txt文件以字符形式读取数组时缺少整数参数错误
- 如何从字符数组C++中提取2个整数并将它们存储在2个变量中(初学者)
- 将矢量的整数内容打印为字符串会导致分割错误
- 如何从文件的输入文本中消除字符/整数