c++ - 如何删除此代码输出的结尾空格

标签 c++

输出以句子结尾,然后是我需要删除的最后一个空格。请帮助!我被难住了!我知道它在最后的 cout 中,但如果我删除最后一个空格,那么整个输出句子就没有空格。这是我第一次使用 C++,所以我在这方面完全是个初学者,而且根本不知道现在该做什么。

#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
#include<iterator>
#include<map>

using namespace std;

map<string, string> myMap;

int contains(string str) {
     map<string,string>::iterator it = myMap.find(str);
     if(it != myMap.end())
     {
     return 1;
     }
     return 0;
     }

 int main() {

     myMap["BFF"] = "best friend forever";
     myMap["IDK"] = "I don't know";
     myMap["JK"] = "just kidding";
     myMap["TMI"] = "too much information";
     myMap["TTYL"] = "talk to you later";
     myMap["IDK."] = "I don't know.";
     myMap["TTYL."] = "talk to you later.";
     myMap["BFF,"] = "best friend forever,";
     myMap["JK,"] = "just kidding,";
     myMap["JK."] = "just kidding.";
     myMap["TMI!"] = "too much information!";
     myMap["TMI."] = "too much information.";


    string text;

    cout << "Enter text: ";
    getline(cin, text);
    cout << "You entered: " << text << endl;
    cout << "Expanded: ";

 stringstream ss(text);
 string item;
 while (getline(ss, item, ' ')) {
     if(contains(item) == 1) {
         cout << myMap[item] << " ";
    } 
    else {
         cout << item << " ";
     }

}


cout << endl;


}

最佳答案

我会通过打印项目之前的空格来解决这个问题。例如:

cout << " " << item;

问题是,现在“Expanded:”后面会有一个额外的空格。您可以通过添加一个“if”语句轻松解决此问题,该语句在启动 while 循环之前打印不带空格的第一个内容:

      if(getline(ss, item, ' ')) {
        if(contains(item) == 1) {
          cout << myMap[item];
        } 
        else {
          cout << item;
        } 
      }
      while(getline....)

或者,您可以删除打印“Expanded:”处的尾随空格:)

关于c++ - 如何删除此代码输出的结尾空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806132/

相关文章:

c++ - flex 没有生成 yyFlexLexer.h header

c++ - 无法使用 this 指针在对象上使用重载的 [] 运算符

c++ - 遍历链表

c++ - 将 Visual Studio 项目设置复制到新项目吗?

C++ 为什么我的单例不维护成员值

c++ - 如何在 C++ 中读取文件时向前查看多个步骤

c++ - 如何使 MinGW 对包含的头文件名区分大小写

c++ - 请告诉我为什么虚函数在以下代码中不起作用

c++ - 可怕的数字不知从何而来

c++ - 获取 lambda 表达式的返回类型