如果一个char是一个空格,在C ++中用'+'替换它 [英] If a char is an empty space, replace it with a '+' in C++
本文介绍了如果一个char是一个空格,在C ++中用'+'替换它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法判断我的程式码有什么问题:
I can't tell what's wrong with my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string test;
cin>>test;
if (test[4] == ' ')
{
test[4] = '+';
}
cout<<test<<endl;
system("PAUSE");
return 0;
}
我基本上要求用户给我一个字符串是星际迷航),然后,我想要的字符串替换为'+'。由于某种原因,我每当我试试这个。但是,当我运行这个,我得到一个对话框,弹出并说调试失败失败和表达式:字符串下标超出范围。
I'm basically asking the user to give me a string (the string will be "star trek") and then, I want the string to be replace with a '+'. For some reason, I'm getting this whenever I try it. However, when I run this, I get a dialog box that pops up and says "Debug Assertion Failed" and "Expression: String subscript out of range".
推荐答案
使用 getline(cin,test)
,因为它不会跳过空格。此外,请使用cin.get()而不是 System(Pause)
。
Use getline(cin,test)
as it won't skip whitespace. Also, please use cin.get() instead of System("Pause")
.
for(int i = 0; i < test.length(); i++) {
if(test[i] == ' ')
test[i] = '+';
}
这篇关于如果一个char是一个空格,在C ++中用'+'替换它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文