如何从文件中读取字符和整数

how to read characters and integers from a file?

本文关键字:字符 整数 读取 文件      更新时间:2023-10-16

所以我有一个看起来像这样的数据文件:

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....
        }
}