0

我有一个文件,其中有一个数字,其中是后面的名称数。例如:

4
bob
jim
bar
ted

我正在尝试编写一个程序来读取这些名称。

void process_file(ifstream& in, ofstream& out)
{
    string i,o;
    int tmp1,sp;
    char tmp2;
    prompt_user(i,o);
    in.open (i.c_str());

    if (in.fail())
    {
        cout << "Error opening " << i << endl;
        exit(1);
    }

    out.open(o.c_str());
    in >> tmp1;
    sp=tmp1;

    do
    {
        in.get(tmp2);
    } while (tmp2 != '\n');

    in.close();
    out.close();
    cout<< sp;
}

到目前为止,我能够阅读第一行并将 int 分配给 sp

我需要 sp 来计算有多少个名字。我怎样才能读懂这些名字。我剩下的唯一问题是如何在忽略第一个数字的情况下获取名称。在那之前我无法实现我的循环。

4

4 回答 4

1
while (in >> tmp1)
        sp=tmp1;

这成功地从第一个读取int然后尝试继续。由于第二行不是int,因此提取失败,因此它停止循环。到现在为止还挺好。

但是,流现在处于fail状态,除非您清除错误标志,否则所有后续提取都将失败。

in.clear()在第一个while循环之后说。

不过,我真的不明白您为什么要编写一个循环来提取单个整数。你可以写

if (!(in >> sp)) { /* error, no int */ }

要阅读名称,请阅读strings。这次循环很好:

std::vector<std::string> names;
std::string temp;

while (in >> temp) names.push_back(temp);

您可能希望在某处添加一个计数器,以确保名称的数量与您从文件中读取的数量相匹配。

于 2013-04-02T10:39:52.793 回答
0
int lines;
string line;
inputfile.open("names.txt");
lines << inputfile;
for(i=0; i< lines; ++i){   
   if (std::getline(inputfile, line) != 0){
      cout << line << std::endl;
   }
}
于 2013-04-02T10:41:19.573 回答
0

首先,假设第一个循环:

while (in >> tmp1)
    sp=tmp1;

是为了读取开头的数字,这段代码应该这样做:

in >> tmp1;

根据手册 operator>>

istream 对象 (*this)。

提取的值或序列不会返回,而是直接存储在作为参数传递的变量中。

所以不要在条件下使用它,而是使用:

in >> tmp1;
if( tmp1 < 1){
     exit(5);
}

其次,永远不要依赖文件格式正确的假设:

do {
    in.get(tmp2);
    cout << tmp2 << endl;
} while ( (tmp2 != '\n') && !in.eof());

尽管整个算法对我来说似乎有点笨拙,但这应该可以防止无限循环。

于 2013-04-02T10:41:22.360 回答
0

这是一个简单的示例,说明如何以您想要的方式从文本文件中读取指定数量的单词。

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

void process_file() {
    // Get file name.
    std::string fileName;
    std::cin >> fileName;

    // Open file for read access.
    std::ifstream input(fileName);

    // Check if file exists.
    if (!input) {
        return EXIT_FAILURE;
    }

    // Get number of names.
    int count = 0;
    input >> count;

    // Get names and print to cout.
    std::string token;
    for (int i = 0; i < count; ++i) {
        input >> token;
        std::cout << token;
    }
}
于 2013-04-02T10:43:34.963 回答