【问题标题】:Not getting output in case of string在字符串的情况下没有得到输出
【发布时间】:2021-04-11 14:25:41
【问题描述】:
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    s[0] = 'a';
    cout << s << endl;
    return 0;
}

我使用了这段代码并运行了,但是没有输出不知道为什么?

但是如果我使用 s = "";然后也没有输出。

但是当我使用 s = " ";那么输出来了,为什么会这样呢?

【问题讨论】:

  • s[0] = 'a'; 是未定义的行为。您无法访问不存在的字符串的位置。 s 在调用时为空,因此 s[0] 超出范围。
  • 但是当我使用 s = " ";然后输出出现为什么会这样? 因为在这种情况下,s 的长度为 1 而不是 0。长度为 1 时,s[0] 将是一个有效的操作。这里要清楚地记住,访问越界索引不会扩展字符串,这样做是未定义的行为/违反了语言规则。

标签: c++ string


【解决方案1】:

您使用的是未初始化的string,因此将a 分配给s[0] 不会执行任何操作或执行未定义的行为。为此,您必须为s 指定一个大小,如下所示:

选项 1:调整大小

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    s.resize(10);
    s[0] = 'a';
    cout << s << endl;
    return 0;
}

选项 2:向后推

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    s.push_back('a');
    cout << s << endl;
    return 0;
}

选项 3:+=

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    s += 'a';
    cout << s << endl;
    return 0;
}

还有更多选择,但我不会把它们放在这里。 (可能是append

【讨论】:

    【解决方案2】:

    请参阅注释here 您正在尝试访问不带任何字符的字符串中的第一个(第零个)字符。这是未定义的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      相关资源
      最近更新 更多