Home > OS >  can someone explain to me why my string is not not showing in output it happens to me a lot and this
can someone explain to me why my string is not not showing in output it happens to me a lot and this

Time:02-05

can someone tell me why s is not showing up.

#include <string>
#include <iostream>

using namespace std;

int main()
{

    string a="1 23";
    string s="";
if(a[1]==' '){s[0]=a[1];

  cout<<s;  }
 
  return 0;
}

CodePudding user response:

You are not allocating any character memory for s to refer to, so s.size() is 0 and thus [0] is out of bounds, and writing anything to it is undefined behavior 1.

1: in C 11 and later, you can safely write '\0' to s[s.size()], but you are not doing that here.

Try this instead:

#include <string>
#include <iostream>
using namespace std;

int main()
{
    string a = "1 23";
    string s = "";
    if (a[1] == ' ') {
        s  = a[1];

        // alternatively:
        s = a[1];

        // alternatively:
        s.resize(1);
        s[0] = a[1];

        cout << s;
    } 

    return 0;
}

Just note that a[1] is the whitespace character ' ', so while you can assign that character to s, and it will print to the console, you just won't (easily) see it visually in your console. Any of the other characters from a would be more visible.

CodePudding user response:

This assignment

if(a[1]==' '){s[0]=a[1];

invokes undefined behavior because the string s is empty and you may not use the subscript operator for an empty string to assign a value.

Instead you could write for example

if(a[1]==' '){s  = a[1];

Pay attention to that in this case the string s will contain the space character. To make it visible you could write for example

#include <iostream>
#include <iomanip>
#include <string>

//...

std::cout<< std::quoted( s ) << '\n';

or

std::cout << '\'' << s << "\'\n";

CodePudding user response:

My guess is that this is a naive attempt to parse the string. Is this what you are looking for?

#include <string>
#include <iostream>

using namespace std;

int main()
{
    string a = "1 23";
    string s;
    if (a[1] == ' ') {
        s = a.substr(2);
        cout << s;
    }
    return 0;
}

CodePudding user response:

Thats because "s" is empty string with size 0. It means there is no element at index [0] in it. When you ask "s" for [0] element it leads to UB.

If you want to add a[1] to "s", you can use:

s.push_back(a[1]);

Or:

s  = a[1];

Or:

s.insert(s.begin(), a[1]); // That's bad way, dont use it.
  •  Tags:  
  • Related