0

I am trying to input strings which may contain white spaces.The entire string can be made of white spaces. Here is what I am doing-

    #include <bits/stdc++.h>
using namespace std;
char arr[1000][1000];
int main()
{
    int t,m=3,n=2;

    cin >> t;
    while(t--)
    {
        string str;        
        for(int i=0;i<m;i++)
        {
            getline(cin,str);
            cout << str[0] << endl;
        }
        return 0;
    }
}

Here t is no of test cases. Say for m=3, I have this input-

1
#T
--
--

For visibility, - is used to represent white spaces.In actual input,there are white spaces instead of - . This is the output I get-

NUL
#
-

Another thing which I tried is this-

for(int i=0;i<m;i++)
{
    for(int j=0;j<n;j++)
        cin >> arr[i][j];
}

where m=3,n=2 for the example above.But printing this arr gives me following output-

#T
NULNUL
NULNUL

I am not sure why I am getting this output.Why am I getting NUL instead of white spaces.Also in the first code, the output I get is NUL before # ,why is that?

2 Answers2

1

There's no need to write such a complicated code to obtain whitespaces from cin. You can just take an advantage of std::noskipws flag.

Solution 1:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;
    char x;
    for (int i=0; i<10; i++)
    {
        cin >> noskipws >> x;
        str += x;
    }
    cout << str;
}

Live demo


Solution 2:

or even simpler, without any string:

#include <iostream>

using namespace std;

int main()
{
    char str[10];
    cin.read(str, sizeof(str));
    cout << str;
}

Live demo


Solution 3:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;
    getline(cin, str);
    cout << str;
}

Live demo

psliwa
  • 1,094
  • 5
  • 9
0

You are printing str[0] - this is not a string, this is a single character. When your string is empty, the only thing it contains is null-terminator ('\0'). And when you access the first element of your string with [], you are accessing this null-terminator. And since you are printing it as a character, you see NUL as your output.

Ilya
  • 4,583
  • 4
  • 26
  • 51
SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • But my string is not empty. It contains two white spaces in this particular space.So printing str[0] should actually print a single white space. –  Aug 24 '15 at 12:56
  • Well, it does not. You've read an empty string. You can verify by printing the whole string, not just the first character. – SergeyA Aug 24 '15 at 13:02
  • 1
    See `cin >> noskipws >> x;` in the answer. According to https://msdn.microsoft.com/en-us/library/ttf4txbf.aspx, "By default, **skipws** is in effect." – Vlad Feinstein Aug 24 '15 at 13:06