简体   繁体   English

没有 output,我的代码有什么问题?

[英]There is no output, What is the wrong with my code?

I am trying to store the reverse of a text stored in (x) in another variable (y), but there is no output!我试图将存储在(x)中的文本的反向存储在另一个变量(y)中,但是没有输出!

#include <iostream>
#include <string>
using namespace std;
int main() { 
    int i=0, j=0;
    string x,y;
    cin>> x;
    for (char c: x) i++;
    for (int j=0; j<i; j=j+1)
        y[j]=x[i-j-1];
    cout <<y;
return 0;
}

在此处输入图像描述

What do you think the size of y is?你认为y的大小是多少?

You never change it's size, so the size stays at zero and this code你永远不会改变它的大小,所以大小保持为零,这段代码

y[j]=x[i-j-1];

is an error because you cannot use [] on a string that has size zero.是一个错误,因为您不能在大小为零的字符串上使用[] Using [] on a string never changes it's size, and it's an error to use [] with an index that doesn't exist for the string.在字符串上使用[]永远不会改变它的大小,并且将[]与字符串不存在的索引一起使用是错误的。

Try this instead试试这个

for (int j=0; j<i; j=j+1)
    y.push_back(x[i-j-1]);

push_back adds a character to the end of a string, increasing the size of the string by one. push_back将一个字符添加到字符串的末尾,将字符串的大小增加一。

BTW an easier way to write this code顺便说一句,编写此代码的更简单方法

i = 0;
for (char c: x) i++;

is

i = x.size();

strings have a size method that tells you what their size is.字符串有一个size方法,可以告诉你它们的大小。

You also could use reverse iterators rbegin/crbegin and rend/crend :你也可以使用反向迭代器rbegin/crbeginrend/crend

#include <iostream>
#include <string>
using namespace std;
int main() { 
    string x,y;
    cin>> x;
    std::copy(x.crbegin(), x.crend(), std::back_inserter(y));
    cout <<y;
    return 0;
}

You did not allocated the memory for y, when you use y[j], actually it doesn't exist, you should resize y, just add the following code after the first for loop您没有为y分配memory,当您使用y[j]时,实际上它不存在,您应该调整y的大小,只需在第一个for循环后添加以下代码

y.resize(i);

Anyway is easier using member and methods of class strig, this is a link with a complete list of them and explanations http://www.cplusplus.com/reference/string/string/无论如何,使用 class 字符串的成员和方法更容易,这是一个链接,其中包含它们的完整列表和解释http://www.cplusplus.com/reference/string/string/

using those, your code will look like the following使用这些,您的代码将如下所示

#include<iostream>
#include<string>
using namespace std;
int main() {
    string x, y;
    cin>>x;;
    for(string::reverse_iterator it=x.rbegin(); it!=x.rend(); it++) {
        y.push_back(*it);
    }
    cout<<y;
} 

iterators are object which you can use for handling containers like the string s, they act as pointers, in this example I used reverse_iterators which are exaclty the same, but they iterate from the last element to the first one.迭代器是 object,您可以使用它来处理像string s 这样的容器,它们充当指针,在此示例中,我使用了完全相同的 reverse_iterators,但它们从最后一个元素迭代到第一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM