使用条件来确定字符串中的元素
Use conditional to determine elements within a string
这是我最后一个问题的扩展(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); // ???
}
}
相关文章:
- 将指针作为缓冲区传递到第一个字符串元素
- C++字符串问题-如何访问字符串元素
- 反转由空格分隔的字符串元素将返回比原始字符串更大的字符串
- 将向量元素与字符串元素进行比较,而不初始化向量
- 如何获取数组中字符串元素的字符数?[C++]
- 如何删除在没有STL的队列中存储在数组中的第一个字符串元素
- 比较两个向量的<Structs>字符串元素
- 将字符串元素转换为整数 (C++11)
- 如何使操作员返回引用字符串元素
- 访问字符串元素地址
- 第一个字符串元素的地址产生意外结果
- 在C 中的字符串向量的字符串元素中循环遍历所有字符
- 将字符串元素分配给结构数组中的结构
- C++检查字符串元素的相等性
- 将字符串元素转换为整数C++
- 试图将字符串元素与循环和索引进行比较,但索引不会增加
- C++ - 链表插入排序(字符串元素)
- C++将二维C字符串元素传递到函数中
- 从字符串元素中获取字符串
- 比较列表<string>和向量<string>中的字符串元素