字符串未由C ++打印 [英] String not being printed by C++

查看:52
本文介绍了字符串未由C ++打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉出现noob问题,我是一名新手程序员,正在从C过渡到C ++.我可以很容易地编写一个程序,以较小的更改以相同的方式用C反转字符串,但是用C ++编写,为什么这样不显示任何内容:

Sorry for the noob question, I'm a newbie programmer and transitioning from C to C++. I could easily write a program to reverse a string in C the same way with minor changes but writing this in C++, why does this not print anything:

#include <iostream>
#include <string>

using namespace std;

int main(){
    string s,p;
    getline(cin,s);
    int j=0,i = 0;
    while(s[i]!='\0'){
        i++;
    }
    i--;
    while(i!=-1){
        p[j] = s[i];
        j++;
        i--;
    }
    cout << p << endl;
    return 0;
}

如果我将p替换为p [2],则它会正确打印出原始字符串的反面第3个字符,但是我找不到打印整个字符串的方法.

if i replace the p with say p[2], it correctly prints out the reverse 3rd character of the original string, but i cant find a way to print the whole string.

推荐答案

要修复字符串反向代码,您只需调整大小字符串对象 p :

To fix your string reverse code you just have to resize the string object p:


int main(){
    std::string s = "hello",
           p;
    p.resize(s.size()); // this was causing your problems, p thought it was size 0

    for (int i = s.size() - 1, j = 0; i >= 0; i--, j++)
    {
        p[j] = s[i];
    }

    std::cout << p << std::endl;
    return 0;
}

除此之外,无需在字符串中找到 \ 0 ,尽管它会存在于其中,您只需询问 std :: string size()是.

In addition to this, there is no need to find \0 in the string, while it will be there, you can just ask std::string what its size() is.

另一方面,默认情况下, std :: string 可能会分配一些内存,只是假设它足以存储您输入的内容将是未定义的行为.

On a side note, while std::string probably allocates some memory by default, just assuming it has enough to store whatever you input is going to be undefined behaviour.

这篇关于字符串未由C ++打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆