比较字符串时如何在c ++中输入函数调用中的输入

时间:2014-02-22 14:07:25

标签: c++

我的代码如下:

#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

class object
{
public:
    string s;
    int a;
    void add()
    {
        cout << "enter name and speed:" << endl;
        cin >> s;
        cin >> a;
        cout << "done" << endl;
    }
};

int main()
{
    int i = 0;
    object o[10];
    string line;
    string a[10];
    // grab a line from standard input
    while (getline(cin, line))
    {
        // break the input in to tokens using a space as the delimeter
        istringstream stream(line);
        string token;
        while (getline(stream, token, ' '))
        {
            // convert string to all caps
            // transform(token.begin(), token.end(), token.begin(), (int(*)(int)) toupper);
            a[i++] = token;
            // print each token on a separate line
            cout << endl << token << endl;
        }
    }
    if (a[0].compare("make") == 0)
    {    
        if (a[1].compare("fan") == 0)
        {
            o[0].add();
            cout << "lol" << endl;
        }
    }
}

我的输出是:

  

使
  风扇
  输入名称和速度:
  做过
  洛尔

问题是我无法输入namespeed的值。它正在跳过并打印donelol。请告诉我如何输入namespeed的值。

以下是文本文件。

  

制作风扇5
     制作a.c 4

1 个答案:

答案 0 :(得分:0)

您的代码永远不会离开第一个

可能应该是这样的事情吗?

while (getline(cin, line)) {

// break the input in to tokens using a space as the delimeter
istringstream stream(line);
string token;
bool flag=false;
while (getline(stream, token,' ')) {

    // convert string to all caps
    //transform(token.begin(), token.end(), token.begin(), (int(*)(int)) toupper);
    a[i++]=token;
    if(i==10)
        flag=true;
    // print each token on a separate line
    cout <<'\n'<< token << '\n';
}
if(flag)
    break;

}