(C++)我似乎不止一次在运行for循环时遇到问题.我做错什么了吗

(C++) I seem to be having trouble running my for loop more than once. Am I doing something wrong?

本文关键字:问题 遇到 什么 循环 for C++ 不止一次 运行      更新时间:2024-05-09

我已经在下面发布了这个问题和我的代码。我基本上试着运行这个循环3次,打印单词的前2个字符。我已经花了一个小时在这个问题上了。我需要知道如何修复它。

问题:编写一个C++程序,使用给定字符串的前2个字符的3个副本创建一个新字符串。如果给定字符串的长度小于2,则使用整个字符串。

样本输入:"abc";"Python";"J";

样本输出:阿巴巴布PyPyPyJJJ

代码:

#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <ctype.h>
#include <algorithm>
using namespace std;
string test(string s1)
{
int x = s1.length();
string y;
if (x >= 2)
{
for (int i = 0; i < 3; ++i)
{
y = s1.substr(0, 2);
return y;
}


}
else
{
for (int j = 0; j < 3; ++i)
{
y = s1;
return y;
}

}
}
int main()
{
cout << test("abc") << endl;
cout << test("Python") << endl;
cout << test("J") << endl;
return 0;
}

这里有一个可能的解决方案:

// Example program
#include <iostream>
#include <string>
std::string test(const std::string& input) {
if (input.length() <= 2) {
return input + input + input;
} else {
std::string tmp(6, '0');
for (int i = 0; i < 3; i++) {
tmp[i*2 + 0] = input[0];
tmp[i*2 + 1] = input[1];
}
return tmp;
}
}
int main()
{
std::string name;
std::cout << test("abc") << "!n";
std::cout << test("Python") << "!n";
std::cout << test("J") << "n";
}

你可以在这个链接上看到它在运行。

以下是如何修复第一个循环

for (int i = 0; i < 3; ++i)
{
y += s1.substr(0, 2); // append two more characters to what we've got so far
}
return y;

还有其他方法可以做到这一点,但这是对代码的最小更改,希望能说明您所犯的错误。

首先,由于一些小错误,您在这里发布的程序无法编译,例如:

for (int j = 0; j < 3; ++i) 
{ 
y=s1; 
return y; 
}

显然++i〃;应替换为"++j":

for (int j = 0; j < 3; ++j) 
{ 
y=s1; 
return y; 
}

此外,您的程序中存在一些逻辑错误。请记住,一旦函数返回,就无法再次恢复。所以在这里你不能用一个循环来";返回3次";,这绝对是错误的。

你可以在函数中完成一个字符串,然后将其打印到屏幕上,这将很容易地解决你的问题。这是我对你的程序的更正:

#include <iostream>
#include <string>
using namespace std;
string test(string s1)
{
int x = s1.length();
string y;
if (x >= 2)
{
string res=s1.substr(0,2);
y=res+res+res;
//Given that the number 3 is very small, repeat it manually may bring a higher efficiency(though it cannot be seen exactly)
return y;
}
else
{
return s1+s1+s1;
}
}
int main()
{
//I do not think this program need so many "#include", just include what we need, that is convenient
//for readers to understand your program quickly :)
cout << test("abc") << endl;
cout << test("Python") << endl;
cout << test("J") << endl;
/*Also, I recommend that you can always test some programs with a dynamic input, so that you can find some 
small mistakes more easily. Below is a simple example:
cout<<"Please input a string:";
string str;
cin>>str;
cout<<test(str)<<endl;*/
return 0;
}

希望我的答案能帮助你解决问题:(