初试牛刀121205

输入一句话,再输入刚才那句话中你想更改的字符串,然后输入要替换的字符串,然后输出。

以下是自己看了书上的例子,自己写的代码,结果悲剧。

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string text;
	cout << "Enter a string terminated by #:  " << endl;
	getline(cin, text, '#');

	string word;
	cout << "Enter the word to be replaced:  " << endl;
	cin >> word;

	string replacement;
	cout << "Enter the replacement word:  " << endl;
	cin >> replacement;

	if (word == replacement)
		cout << "The word and its replacement are the same.  " << endl;
	
	size_t start = text.find(word);

	while (start != string::npos)
	{
		text.replace(start, word.length(), replacement);
		cout << "Your string is now: " << text <<endl;

	};


	return 0;
}

输出结果惊人:(无法上图,算了,总之是一个循环无限下去)


如果输入的待更改字符串与替换字符串相同的话,即word == replacement:


所以对照一下书上代码,发现症结所在。

第一个问题;while循环中,首先看条件,只要start不等于string::npos就一直循环,问题就出在这里了,为什么它会一直搞下去,因为,没有检测到string::npos。所以应该在循环中加入一个递增,这也是基本常识

                   start = text.find(word, start + replacement.length());

还有,需要把while循环中的输出写到结尾,如果text中有多个要替换的word输出会出现多个渐变的输出结果,而我们需要的是最后一个结果。

                   text.replace(start, word.length(), replacement);

                   cout << "Your string is now: " << text <<endl;

                   start = text.find(word, start + replacement.length());

第二个问题;同样if循环中,既然出错了就需要一个终止。

                   cout << "The word and its replacement are the same.  " << endl;

                   exit(1);

 

最终代码更改以后

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string text;
	cout << "Enter a string terminated by #:  " << endl;
	getline(cin, text, '#');

	string word;
	cout << "Enter the word to be replaced:  " << endl;
	cin >> word;

	string replacement;
	cout << "Enter the replacement word:  " << endl;
	cin >> replacement;

	if (word == replacement)
	{
		cout << "The word and its replacement are the same.  " << endl;
		exit(1);
	}
	
	size_t start = text.find(word);

	while (start != string::npos)
	{
		text.replace(start, word.length(), replacement);
		start = text.find(word, start + replacement.length());

	}

	
	cout << "Your string is now: " << text <<endl;


	return 0;
}

得以实现——牛刀小试,以失败告终!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值