/* Write a program that would mix-and-merge two given strings (s1 and s2) into string s3 as follows:
first character of s1, first character of s2, second character of s1, second character of s2, etc. */
我在互联网上找到了这个示例练习,我想我会尝试一下。 一切似乎都没问题,代码编译没有错误,但我的" s3"字符串变量不会输出任何内容,它只会保持空白。
有趣的是,但问题似乎是在返回0之前的最后一行;
cout << s3;
如果我做这样的事情:
cout << s3[0];
或者我想要的任何索引,它将在运行代码时显示正确的字符,该代码是从其他字符串连接的。那么问题是什么? 代码在此供参考:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string s1, s2, s3;
int i;
int j = 0;
cout << "Type in the first string: ";
getline(cin, s1);
cout << "Type in the second string: ";
getline(cin, s2);
for(i = 0; j < s1.size(); i += 2) // Merge first string by starting at index 0 and moving in 2s hence i += 2.
{
s3[i] = s1[j];
++j;
}
j = 0;
for(i = 1; j < s1.size(); i +=2) // Merge second string by starting at index 1 hence i + 1 and again moving in 2s as to not overwrite an index that s1 put in.
{
s3[i] = s2[j];
++j;
}
cout << s3; // Problem is here?
return 0;
}
答案 0 :(得分:2)
使用大于当前长度的运算符s3
访问[i]
字符串是未定义的行为。
您可以尝试在循环之前使s3
足够大(例如填充空格)。请注意,您的当前实现仅在两个字符串长度相同时才有效。
或者,尝试以不同的方式思考。例如如果你在你面前的小纸叠(每件上有一个字母)上有字符串s1
和s2
并希望将它们合并到一个堆栈中,那么你会这样做。< / p>
答案 1 :(得分:1)
在您的代码中只添加了一行并使其正常工作:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string s1, s2, s3;
size_t i;
size_t j = 0;
cout << "Type in the first string: ";
getline(cin, s1);
cout << "Type in the second string: ";
getline(cin, s2);
s3.resize(s1.size() + s2.size());
for(i = 0; j < s1.size(); i += 2) // Merge first string by starting at index 0 and moving in 2s hence i += 2.
{
s3[i] = s1[j];
++j;
}
j = 0;
for(i = 1; j < s1.size(); i +=2) // Merge second string by starting at index 1 hence i + 1 and again moving in 2s as to not overwrite an index that s1 put in.
{
s3[i] = s2[j];
++j;
}
cout << s3; // Problem is here?
return 0;
}
虽然这仅适用于大小相同的s1
和s2
。