无法打印字符串(C ++)

时间:2018-03-11 05:06:06

标签: c++ string c++14

在将一个字符串的每个值分配给另一个字符串后,我无法打印该字符串。如何克服这个问题

#include <bits/stdc++.h>

using namespace std;

int main()
{
  int n, k;
  string s = "Nikhil", shiftedS;
  n = s.length();
  cin >> k;

  for (int i = 0; i < n; i++)
  {
    int idx = (i + k) % n;
    shiftedS[idx] = s[i];
  }
  shiftedS[n] = '\0';

  for (int i = 0; i < n; i++)
    cout << shiftedS[i] << " ";
  cout << shiftedS; // I am unable to print when I try like this.

  return 0;
}

2 个答案:

答案 0 :(得分:0)

为什么不试试这个

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,k;
string s="Nikhil",shiftedS = "";
n=s.length();
cin>>k;
for(int i=0;i<n;i++)
{
    int idx=(i+k)%n;
    shiftedS+=s[i];
}
cout<<shiftedS;
return 0;
}

答案 1 :(得分:0)

您正在获得不可预测的行为,因为shiftedS是一个空字符串。如果你像这样初始化它

string shiftedS(n, ' ');    // n is equal to length of "Nikhil"

并摆脱shiftedS[n] = '\0';(C ++字符串对象不需要这个),它应该按预期工作。我尝试了这些变化,它对我有用。

相关问题