scanf 跳过具有已定义大小的字符串并进行 space

scanf skipping string with a defined size with a proceeding space

我正在尝试读取 3 个不同的字符串,每个字符串最多 15 个字符。当我尝试用 scanf("%s %s %s", a, b, c) 读取它们时,只有最后一个被拾取(我假设每个字符串之间的 spaces 与此有关)。

#include <iostream>
#include <string.h>

using namespace std;

#define DIM 15

int main()
{
    char a[DIM], b[DIM], c[DIM];

    scanf("%s %s %s", a,b,c);
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cout << "Cadenes introduides: " << a << " " << b << " " << c << endl;
}

输入是CadenaDe15chars CadenaDe15chars CadenaDe15chars

我只看到



CadenaDe15chars
Cadenes introduides:   CadenaDe15chars

当实际输出应该是

CadenaDe15chars
CadenaDe15chars
CadenaDe15chars
Cadenes introduides: CadenaDe15chars CadenaDe15chars CadenaDe15chars

我对 C++ 有点陌生,所以我真的不知道如何让 scanf 忽略白色space,我找到了用新行分隔的字符串的例子 \n,但不是 space.

这次通话

scanf("%s %s %s", a,b,c);

调用未定义的行为,因为至少此输入“CadenaDe15chars”包含 15 个字符。因此附加的终止零字符 '\0' 将由用作参数的相应数组外部的函数写入。

你至少应该像这样声明宏常量

#define DIM 16

在数组中保留 space 用于可能附加的零字符。

鉴于您的约束(没有 0 终止),我会读取输入 char-by-char,将它们添加到适当的数组并处理 white-space 字符以转到下一个数组。

请注意,数组 char a[DIM] 不必以 0 结尾。但是,您将无法使用它和 C-string API,包括 cin << ...

代码示例。您可以先将一行读入 std::string 变量。

#include <iostream>
#include <string>

const int DIM = 15;

int main()
{
    char a[DIM], b[DIM], c[DIM];
    int a_len(0), b_len(0), c_len(0);

    std::string s = "CadenaDe15chars CadenaDe15chars CadenaDe15chars";

    int ind = 0;
    for (; a_len < 15; ++a_len, ++ind) {
        if (std::isspace(s[ind]))
            break;
        a[a_len] = s[ind];
    }
    while (std::isspace(s[ind]))
        ++ind;

    for (int i = 0; i < a_len; ++i)
        std::cout << a[i];
    std::cout << std::endl;
}

重复 bc,或使用 two-dimensional 数组。