Home > other >  scanf skipping string with a defined size with a proceeding space
scanf skipping string with a defined size with a proceeding space

Time:02-01

I'm trying to read 3 different strings of max 15 characters each. When I try to read them with scanf("%s %s %s", a, b, c), only the last one is picked up (I'm asuming the spaces between every string has something to do with this).

#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;
}

the input is CadenaDe15chars CadenaDe15chars CadenaDe15chars

And I'm only seeing



CadenaDe15chars
Cadenes introduides:   CadenaDe15chars

when the actual output should be

CadenaDe15chars
CadenaDe15chars
CadenaDe15chars
Cadenes introduides: CadenaDe15chars CadenaDe15chars CadenaDe15chars

I'm kinda new to c so I don't really know how to make scanf ignore the whitespace, I've found examples with strings delimited by a new line \n, but not with a space.

CodePudding user response:

This call

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

invokes undefined behavior because at least this input "CadenaDe15chars" contains 15 characters. So the appended terminating zero character '\0' will be written by the function outside the corresponding array used as an argument.

You should at least declare the macro constant like

#define DIM 16

to reserve space in the arrays for potentially appended zero character.

CodePudding user response:

Given your constraints (no 0-termination), I would read the input char-by-char, adding them to an appropriate array and processing white-space character to go to the next array.

Note that the array char a[DIM] does NOT have to be 0-terminated. However, you won't be able to use it and a C-string APIs, including cin << ...

Code example. You can read a line into the std::string variable first.

#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;
}

Repeat for b and c, or use two-dimensional array.

  •  Tags:  
  • Related