c++ - 为什么我的解析字符串代码有额外的空间?
问题描述
我的作业代码有问题。一切都正确输出,除了我在“第一次”输出后获得了额外的空间。我的代码如下所示,请帮助我修复额外的空间。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string userStr;
bool inputDone = false;
while(!inputDone)
{
bool commaCheck = false;
do
{
cout << "Enter input string:" << endl;
getline(cin, userStr);
if (userStr == "q")
{
inputDone = true;
break;
}
else{
for (unsigned int i = 0; i < userStr.length(); i++)
{
if (userStr[i] == ',')
commaCheck = true;
}
if (!commaCheck)
{
cout << "Error: No comma in string." << endl << endl;
}
}
} while (!commaCheck);
if(!inputDone)
{
string first, second;
istringstream stream(userStr);
getline(stream, first, ',');
stream >> second;
cout << "First word: " << first << endl;
cout << "Second word: " << second << endl;
cout << endl;
}
}
return 0;
}
解决方案
如果您使用std::getline(stream, first, ',');
并且您的单词和逗号之间有空格,那么它当然会在first中。因为你告诉std::getline
我:在你看到逗号之前把所有东西都给我。
如果有人输入“a,b”,那么你首先有前导和尾随空格。
您需要“修剪”您的字符串,这意味着删除前导和尾随空格。
在 SO 上发布了许多修剪功能。请在此处查看示例
如果您发现其他问题,请告知
推荐阅读
- swift - Swift IAPManager SKPaymentTransactionObserver 未调用
- swift - 源文件中的 Xcode Editor PlaceHolder
- matlab - 有没有办法在 Matlab 中使用具有不同尺寸元素的表格来操作 K-Nearest-Neighbot 分类?
- java - 在 Spring Data JPA 中的本机查询之间共享 SQL
- java - 使用当前坐标调用 glTranslatef 以恒定速度移动对象(OpenGL ES 1.1)
- asp.net-mvc-5 - 使用 (SqlDataReader reader = cmd.ExecuteReader()) 错误 asp.net mvc5
- xamarin - 编辑 Tizen 清单文件
- r - 如何在R中的许多矩阵列表上平均相同的单元格
- sql - spark数据帧中IFNULL和IFF的等效SQL函数
- swift - 如何使用 UIPanGestureRecognizer 以 180 度角对 CALayer 进行 3Drotate 和 3Dtranslate?