Hernando Abella
Hernando Abella

Reputation: 326

Unexpected return from cin.getline() in C++

I have this problem that when I use getline() function to input a char array it also inserts other characters, that are not constant and change every time I run the program.

I do realize it is most likely because of some kind of overflow happening, and it just takes numbers from the RAM.

But is there a possibility to fix that? (Program is supposed to reverse a string and remove any non-letters, excluding spaces)

Here is my program:

#include <iostream>
#include <ctype.h>
#include <string>
using namespace std;

int main() {
    string decoded = "";
    char text[100]; 
    cin.getline(text,sizeof(text));
    for(int i = sizeof(text)-1; i >= 0; i--){
        if (isalpha(text[i]) || text[i] == ' ' )
            decoded.push_back(text[i]);
    }
    cout << decoded;
    return 0;
}

Upvotes: 0

Views: 101

Answers (2)

allMight
allMight

Reputation: 356

Add #include <string.h> and change

for(int i = sizeof(text)-1; i >= 0; i--){ to

for(int i = strlen(text)-1; i >= 0; i--){

because strlen(text) calculates length upto \n where as sizeof(text) includes \n too.

or as Ruks mentioned in the comment a simple initialization char text[100] {}; works.

Upvotes: 1

Vaibhav Mahajan
Vaibhav Mahajan

Reputation: 222

Just declare text as an empty array same as char[] text = new char[]{};

Upvotes: 0

Related Questions