然后在C ++中逐行读取字符串

时间:2016-04-18 00:30:38

标签: c++ file-io

所以,我有一个包含字符串模式的文件,然后是逐行交替的int。

这样的事情:

John McClane
30
James Bond
150
Indiana Jones
50

在这个例子中,我将John McClane设置为字符串变量,然后将30设置为整数变量。我的问题是处理两种类型。我想使用getline(),但这仅适用于字符串。

这样做是否有效或“正确”?

5 个答案:

答案 0 :(得分:1)

您可以尝试多种方法。

  • 获取字符串输入,如果有效,则转换为整数
  • 将每秒字符串转换为整数
  • 尝试读取一个整数(只需使用cin >> in;)。如果您想要一个强大的程序,您可以使用cin.good()
  • 检查有效性

我不知道是否有一种“正确”的方式来做到这一点,但这不是一个非常繁重的操作,所以无论你选择什么都应该没问题。

答案 1 :(得分:0)

你可以像这样制作一个变量

string ibuf;

然后将其转换为执行此操作的整数

getline(cin, ibuf);
(Whatever your int variable is) = strtol(ibuf.c_str(), NULL, 10);

答案 2 :(得分:0)

关于C ++的一件事是,有很多方法可以完成任何一项任务。从字符串获取整数的一种方法是使用字符串流。有关stringstreams here

的教程

至于阅读交替文件的问题,请考虑以下伪代码:

boolean isInt  = false;
while(fileIsNotOver) {
        //getline
    if(isInt) {
        //use stringstream to get int here
    } else {
        //do whatever with the name here
    }
    isInt = !isInt;
}

答案 3 :(得分:0)

我不知道这是否完全有效,因为我没有测试它,但它只是编译得很好,答案应该像我想的那样。

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

using namespace std;

int main()
{
    int counter = 0;
    int number;
   string test_string;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,test_string) )
    {
     cout << test_string << '\n';
      ++counter;

      if(counter % 2 == 0 ){
            number = atoi(test_string.c_str()); 
          cout << number << '\n';            
      }else{

           cout << test_string << '\n';
      }
    }


    myfile.close();
  }

  else cout << "Unable to open file";

    return 0;
}

答案 4 :(得分:0)

你可以尝试这样读取一个字符串然后逐行交替。

#include<iostream>
#include<string>
#include<cstdio>
using namespace std;

int main()
{
    string name;
    int number;
    freopen("input.txt", "r", stdin);
    while (getline(cin, name))
    {
        cin >> number;
        /*
        process the input here
        ...
        ...
        */
        getline(cin, name); // just to read the new line and/or spaces after the integer
        //getchar();   //you can use getchar() instead of getline(cin, name) if there is no spaces after the integer
    }
    return 0;
}

谢谢!!!

相关问题