字符串计算后添加空字符

时间:2016-08-08 14:22:55

标签: c++

我正在尝试直接使用

打印字符串“ans”
cout << ans;

而不是对字符串的每个字符进行循环。这是我编写的完整代码(字符串anss具有相同的大小)。

PS:程序接受一个字符串并打印与其移动键盘字符相关联的相应数字。(如b c将给出2,d e f将给出3)

(因此字符串abcdef将打印222333,这就是字符串anss具有相同大小的原因)

PS:我在评论中写了问题所在。

#include<iostream>
char has[]={'2','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','7','7','7','8','8','8','9','9','9','9'};
using namespace std;
int main()
 {
    //code
         int t;
         cin>>t; 
         while(t)
         {
            string s,ans;
            int i;
            cin>>s;
            for(i=0;i<s.length();i++)
            {
                ans[i]=has[s[i]-'a'];
            }
            ans[i]='\0';
            cout<<ans;  // **Does not printing string "ans" Why?****

            for(i=0;i<s.length();i++) 
            cout<<ans[i];  // **printing the string "ans" but using loop**

            cout<<endl;
            //**some other methods I found in forum commented them**
            //string str(ans);
            //cout<<str.c_str();

              t--;
         }
    return 0;
}

3 个答案:

答案 0 :(得分:4)

std::string初始化为空字符串。您正在通过ans访问operator[],但这不会在字符串中添加字符。以这种方式访问​​不存在的索引是未定义的行为,遗憾的是,这不会导致崩溃,因为这会对错误提示。

可能的解决方案:如果您想继续使用operator[]或使用std::stringstream来形成所需的字符串,请将字符串初始化为所需的长度。

BTW:std::string不需要终止空字符。

答案 1 :(得分:2)

这段代码几乎完全是胡说八道。

cin >> s之后,s可以是任何东西(无论是什么序列,不管是多长的字符:只需让你的猫在键盘上随机输入。它唯一不会有......空格)

因此s[i]-'a'可以是-128到+127之间的任何内容 因此has[s[i]-'a']主要是未定义的行为。 即使是h中的某个字符,ans[i]是&#34;越界&#34;,ans被宣布为空(我完全是真的无法弄清楚什么&#34; ans和s的大小相同&#34;在你的问题意味着。

毕竟,你想要做的目的仍然完全模糊不清......

答案 2 :(得分:0)

首先,您的代码中存在多个错误

// Assuming you're using std::string
string ans; // empty string
string s; // another empty string
cin>>s; // 's' now have some data
char has[]={'2','3','4','5'};
for(i=0;i<s.length();i++)
{
    ans[i]=has[s[i]-'a'];// here you might go out of bounds of 'has'
    cout << ans[i] << " ";
}
ans[i]='\0';
cout<<ans; 

假设您的输入永远不会导致has越界(这是未定义的行为)

我将从operator[]的{​​{1}}开始。 documentation表示它不执行边界检查(因此可能无法检测到您的错误),并且std::string如果修改了此字符,则行为未定义。

最后,您要添加一个终止空符号,以便将其与pos == size()一起使用。这个动作是多余的。但是如果你真的需要一个以空字符结尾的字符串(也称为c-string),你可以使用特殊的函数string::c_str()来完成它。

考虑到所有这些,正确的代码将如下所示:

cout