【问题标题】:String Altering Program Outputting Random Characters输出随机字符的字符串修改程序
【发布时间】:2017-01-31 01:28:39
【问题描述】:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string output;
string words;
int i;

int main()
{
    cin >> words; // gets words from user
    output = ""; // readys the output string
    i = 0;      // warms up the calculator
    int size = words.size();  // size matters
    while (i <= size) { // loops through each character in "words"       (can't increment in the function?)
        output += ":regional_indicator_" + words[i] +':';  //     appends output with each letter from words plus a suffix and prefix
        ++i;
    }               

    cout << output << endl; // prints the output
    return 0;
}

我想考虑一下我对这段代码的意图很清楚。只需取一个句子,用该字符+后缀和前缀替换所有字符。 我的问题是,在调试器中运行时,我会输入"hello world",程序会输出"osss"

我完全没有 C++ 方面的教育,在这里完全不知所措。是我的++i吗?

【问题讨论】:

  • cin &gt;&gt; words; 只会读取一个单词,而不是一行中的所有单词。
  • 您不能使用+ 连接字符串文字和字符。其中一个参数必须是std::string

标签: c++ string input output


【解决方案1】:

这一行:

output += ":regional_indicator_" + words[i] +':';  //     appends output with each letter from words plus a suffix and prefix

不起作用。仅当参数之一是 std::string 时,用于字符串连接的 + 运算符的重载才有效。但是您尝试将它与 C 字符串文字和 char 一起使用。将其更改为:

output += "regional_indicator_";
output += words[i];
output += ':';

这为每个部分使用std::string+= 重载,并执行您想要的操作。

另外,如果您想阅读整行,而不仅仅是一个单词,请使用:

getline(cin, words);

【讨论】:

  • 非常感谢!工作得很好,我在它周围抛出了一个 if 循环来处理空格。今晚我将开始阅读 Kerninghan 和 Ritchie,这样我就不必再问任何愚蠢的问题了。
猜你喜欢
  • 1970-01-01
  • 2018-03-17
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 2017-03-19
  • 1970-01-01
相关资源
最近更新 更多