从文件中读取前n个字母到字符串?

时间:2014-04-14 15:43:42

标签: c++ file-io

我对编程很新,现在我正在做一个练习,我应该使用一个循环从文件中读取25个第一个符号,其中包含25个字母的字符串(如果名称短于25)和两个数字。例如:

Whirlpool machine         324 789.99

我想它看起来应该是这样的:

ifstream info("Information.txt");
string str;
int a;
double b;
for(int i = 0; i < 25; i++)
{ // some kind of code to get first 25 symbols into a string.
}
info >> a >> b;

我似乎无法找到合适的代码来直接获得25个字符串。有什么建议吗?

4 个答案:

答案 0 :(得分:2)

您可以将std::copy_n()算法与流缓冲区迭代器一起使用:

std::string str;

std::copy_n(std::istreambuf_iterator<char>(info.rdbuf()),
            25, std::back_inserter(str));

您可能更熟悉的方法是将get()for()循环一起使用:

for (char c; str.size() != 25 && info.get(c); )
    str += c;

答案 1 :(得分:2)

一种简单的方法是使用read()来读取给定数量的字符:

int length = 25;             // num of chars you want to read
str.resize(length, ' ');     // reserve spaces
char* begin = &*str.begin();
info.read(begin, length);    // <- read it here

答案 2 :(得分:0)

您可以将所有文件内容读入字符串列表,然后将最后两个值提取到数字变量。

int main(int argc, char* argv[])
{
    ifstream info("ReadMe.txt");

    list<string> str;
    int a;
    double b;

    while(!info.eof())
    {
        char value[255];
        info >> value;
        str.push_back(value);
    }

    b = strtod(str.back().c_str(), 0);
    str.pop_back();

    a = (int)strtol(str.back().c_str(), 0, 0);
    str.pop_back();

    return 0;
}

答案 3 :(得分:0)

鉴于上下文,我将整行读入一个字符串,使用 std::getline,然后提取子字符串。类似的东西:

std::string line;
while ( std::getline( info, line ) ) {
    std::string header = line.substr( 0, 25 );
    //  and later...
    std::istringstream rest( line.substr( 25 ) );
    int a;
    double b;
    rest >> a >> b;
    //  ...
}

一般来说,在读取面向行的输入时,读取行, 然后使用std::istringstream来解析它。或者,如果有的话 你可以“按原样”使用的部件(就像这里的情况一样),按原样使用它们。

相关问题