尝试从ASCII文件中读取行使用C ++,Ubuntu和Mac ...? [英] Trying to read lines from an ASCII file using C++ , Ubuntu vs Mac...?

查看:155
本文介绍了尝试从ASCII文件中读取行使用C ++,Ubuntu和Mac ...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASCII文件(students.txt),如下所示(忽略空行,它们是我对此格式工具不熟悉的工具):

  stella 10 4.4 ... 
peter 1.1 5 ...

也就是说,每一行都以一个名称开头,后跟一个或多个数字。



下面的代码片段是一行一行地读取的,将名称读入字符串,并将数字转换为双精度,依次打印这些。当我在Ubuntu上运行它时,它运行正常,我得到

  stella 10 4.4 
peter 1.1 5 $ b $但是,当我在Mac上运行它时,我得到以下结果:







$ b b $ b

  stella 10 4.4 
ter 1.1 5


$ b b

但是,当我将peter改为speter时,它运行正常...:

  stella 10 4.4 
speter 1.1 5

任何想法...?

  #include< iostream> 
#include< fstream>
#include< string>

using namespace std;


int main(){

ifstream intile(students.txt);
string name;
double x;

while(!infile.eof()){
infile>>名称;
cout<<名称<< '';
while(infile>> x){
cout<< x<< '';
}
cout<< endl;
if(!infile.eof())
infile.clear();
}

return 0;
}


解决方案

成行,通常最容易通过行读取它们,然后将它们分成组件:

  std :: string line; 

std :: string name;
std :: vector< double>值;

while(std :: getline(infile,line)){
std :: isTringstream buffer(line);
double temp;

buffer>>名称;
while(buffer>> temp)
values.push_back(temp);
}


I have an ASCII file (students.txt) that looks as follows (Ignore empty lines, they're an artifact of my unfamiliarity with this formatting tool):

stella 10 4.4 ...
peter 1.1 5 ...

That is, each line starts with a name, followed by one or more numbers.

The code snippet below is meant to read this file line by line, reading the name into a string and the numbers into a double, printing each of these in turn. When I run this on Ubuntu, it works fine and I get

stella 10 4.4
peter 1.1 5

However, when I run it on a Mac, I get the following:

stella 10 4.4
ter 1.1 5

When I change 'peter' to 'speter', however, it works fine...:

stella 10 4.4
speter 1.1 5

Any thoughts...?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main() {

  ifstream infile("students.txt");
  string name;
  double x;

  while ( !infile.eof() ) {
    infile >> name;
    cout << name << ' ';
    while ( infile >> x ){
      cout << x << ' ';
    }
    cout << endl;
    if (! infile.eof() )
      infile.clear();
  }

  return 0;
}

解决方案

When the input starts out divided into lines, it's usually easiest to read it by lines, then split those into the component pieces:

std::string line;

std::string name;
std::vector<double> values;

while (std::getline(infile, line)) {
    std::istringstream buffer(line);
    double temp;

    buffer >> name;
    while (buffer >> temp)
        values.push_back(temp);
}

这篇关于尝试从ASCII文件中读取行使用C ++,Ubuntu和Mac ...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆