简体   繁体   English

cout字符串不会在屏幕上打印任何内容

[英]cout a string aint printing anything to the screen

Its a simple string manipulation question.Shift each chara in the string by 2 positions to the right. 这是一个简单的字符串操作问题。将字符串中的每个字符右移2个位置。

I used a second string to copy the characters from first string to the desired position in the second string. 我使用第二个字符串将字符从第一个字符串复制到第二个字符串中的所需位置。 But cout ain't printing the second string. 但是cout不会打印第二个字符串。 If I try to print the string like in the comment it work. 如果我尝试像在注释中那样打印字符串,它将起作用。 BUt why cout<<dups won't work? 为什么cout<<dups不起作用?

#include<iostream>
 #include<string>
 using namespace std;
 int main()
 {
     string s;
     string dups;
     cin>>s;
     int k;
     cin>>k;
     for(int i=0;s[i];i++)
     {
         int idk = (i+k)%6;
         dups[idk] = s[i];
     }
      dups[6] = '\0';
      cout<<dups;


     /*for(int i=0;dups[i];i++)
        cout<<dups[i]; */
 }

input: hacker 2 output: erhack 输入:黑客2输出:erhack

first cout ain't printing anything. 第一球什么都没印。 if i do like in the comments it works. 如果我在评论中喜欢它的话。

You have undeined behavior everywhere because you default initialized your string(zero size) and access out of bounds: 您到处都有不确定的行为 ,因为您默认初始化了字符串(零大小)并超出了范围:

string dups;

One fix is 一种解决方法是

string s;
cin>>s;
string dups = s;

if i do like in the comments it works. 如果我在评论中喜欢它的话。

You may have successfully written to some memory location when you did this: 执行此操作时,您可能已成功写入某些内存位置:

string dups;              // dups.size() == 0 after this
...
    dups[idk] = s[i];     // You write to memory you don't "own".

And you may be able to retrieve the same data when extracting it like this: 这样提取数据时,您也许可以检索相同的数据:

for(int i=0;dups[i];i++)  
    cout<<dups[i];        // dups.size() is still 0

But it's just appearing to work. 但这似乎起作用了。 The memory you've written to may be overwritten by just about anything so you can't expect it to give you the correct result. 您写入的内存可能会被几乎所有内容覆盖,因此您无法期望它会为您提供正确的结果。 The behaviour of the program is undefined. 该程序的行为是不确定的。 Anything can happen. 什么都可能发生。

You can fix it by resizing dups when you know how many characters it needs to contain: 您可以通过调整解决它dups当你知道它需要多少字符包含:

cin>>s;
dups.resize(s.size());

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

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