I am trying to take sentence as an input from the user in the below code. eg. Input -
9
do or die
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Enter the length of the sentence: ";
cin>>n;
cin.ignore();
char array[n 1];
cin.getline(array,n);
cin.ignore();
cout<<array[7]<<endl;
cout<<array[8]<<endl;
While printing the array[7], I am getting 'i' as my output, but while printing array[8] I am expecting 'e' as my output but I did not get anything as an output. I have declared character array of size (n 1), which means array[n] should be null character but why array[8] is coming out to be null character?
Am I doing wrong somewhere?
CodePudding user response:
std::istream::getline(char* s, streamsize n):
- Extracts characters from the stream as unformatted input and stores them into s as a c-string.
- n is the maximum number of characters to write to s, including the terminating null character.
If you want to read your 9 characters of the sentence, not only your buffer needs to be 10 characters long, but also n in getline needs to be 10.
https://www.cplusplus.com/reference/istream/istream/getline/
CodePudding user response:
The answer to the actual problem is addressed by @SKCoder, so I just want to add that input handling works better with std::string and I changed the code accordingly:
#include <iostream>
int main(){
size_t n;
std::cout<<"Enter the length of the sentence: ";
std::cin>>n;
std::cin.ignore();
std::string str;
std::getline(std::cin, str);
std::cin.ignore();
std::cout<<str.substr(str.length()-2, 2)<<"\n";
std::cout << (str.length() != n? "length is wrong": "length is correct") << "\n";
}
I usually don't use using namespace std; to avoid namespace clashes, but in this case it may make sense.
Using a string, you don't need the length anymore, so you can use it to test valid input.
