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

C++ (C+;+;)我似乎不止一次运行for循环时遇到问题。我做错什么了吗?,c++,C++,我已经把问题和我的代码贴在下面了。我基本上试着运行3次for循环来打印单词的前2个字符。这个问题我已经花了一个小时了。我需要知道如何修理它 问题: 编写一个C++程序,使用给定字符串的前2个字符的3个副本来创建一个新的字符串。如果给定字符串的长度小于2,则使用整个字符串 样本输入: “abc” “Python” “J” 样本输出: 阿巴巴 派皮 JJJ 代码: #include <iostream> #include <strin

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

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

样本输入: “abc” “Python” “J”

样本输出: 阿巴巴 派皮 JJJ

代码:

            #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;
            }
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
字符串测试(字符串s1)
{
int x=s1.length();
弦y;
如果(x>=2)
{
对于(int i=0;i<3;++i)
{
y=s1.substr(0,2);
返回y;
}
}
其他的
{
对于(int j=0;j<3;++i)
{
y=s1;
返回y;
}
}
}
int main()
{

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

// 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";
}

//示例程序
#包括
#包括
标准::字符串测试(常量标准::字符串和输入){

if(input.length()下面是如何修复第一个循环

  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 i=0;i<3;++i)
{
y+=s1.substr(0,2);//在我们得到的内容后面再加上两个字符
}
返回y;

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

首先,由于以下一些小错误,您在此发布的程序无法编译:

for(int j=0;j<3;++i)
{ 
y=s1;
返回y;

}
这里有一个技巧。如果你想让一个循环运行三次,不要在循环中放一个返回。返回退出函数(从而停止循环)立即。使用循环收集您想要的结果,然后在循环完成后返回该结果。此外,您还必须连接字符串。到目前为止,您的工作没有问题。但建议在答案中添加一些有关解决方案的说明,以使将来的读者更清楚。如果可行,请在中添加一些注释代码使它更漂亮。