使用条件来确定字符串中的元素

Use conditional to determine elements within a string

本文关键字:字符串 元素 条件      更新时间:2023-10-16

这是我最后一个问题的扩展(istringstream重复的最后一项?)。

我需要确定一个字符串包含两个还是三个数据。我使用"如果"条件来确定这一点,但是我没有得到我希望的结果-我意识到我错过了一些东西。

if的第一部分检查是否只有名字和年龄-如果这不起作用,它应该尝试下一部分(my else if),它允许三个-其中有first, last和age。当我尝试第一个,最后一个和年龄时,这是不工作的(尽管如果我只有第一个和年龄),并且我从底部else语句获得结果-这意味着其他两个失败了。这可以解释给我,并可能帮助我修复我的代码,所以它做什么我之后?非常感谢你的帮助!我的代码是:
#include <iostream>
#include <string>
#include <list>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
    string first;
    string last;
    string fullName;
    int age;
    //string number;
    string inputText("Jane Smith 18");
    istringstream iss(inputText);

    if (iss >> first >> age)
    {
        cout << "Only first and age detected.";
    }
    else if (iss >> first >> last >> age)
    {

        while (iss >> first >> last >> age)
        {
            iss >> first >> last >> age;
            fullName = first + " " + last;
            cout << fullName << " " << age << endl;
        }
    }
    else
    {
        cout << "Failed";
    }

    system("pause");
    return 0;
}

问题

下一行

中的条件
if (iss >> first >> age)

求值为false,因为不能从字符串中提取age

下一行

中的条件
else if (iss >> first >> last >> age)

不能从iss中提取任何输入,因为iss已经处于错误状态。条件的计算结果为false

表示语句

下的代码块
else
执行

.

一个解

// Extract the first name
if ( !(iss >> first) )
{
   // If we fail to extract the first name, the string is not right.
   // Deal with error.
   cout << "Failed" << endl;
   exit(0); // ???
}
// Try to extract age.
if ( iss >> age )
{
   // Age was successfully extracted.
   cout << "Only first and age detected.";
}
else
{
   // Clear the error state of the stream.
   iss.clear();
   // Now try to extract the last name and age.
   if ( iss >> last >> age )
   {
      fullName = first + " " + last;
      cout << fullName << " " << age << endl;
   }
   else
   {
      // Deal with error.
      cout << "Failed" << endl;
      exit(0); // ???
   }
}