Issue
#include <iostream>
void main()
{
using namespace std;
char sentence[2000];
for (int i = 0; i <= 2000; i++) {
char Test;
cin >> Test;
if (Test != '\r') sentence[i] == Test;
else break;
}
for (int i = 0; i <= 2000; i++) {
cout << sentence[i];
}
}
Why does my function for inputting a string not work? I wrote this program that is supposed take in input from the user and display the sentence back when the user hits enter. I know there are functions in C++ to do this but I want to write such a program myself. I am a beginner so please keep the answer beginner friendly. I want to know why this doesn't work and also how to make it work. What happens when I run this program is that the input keeps going even thought I hit enter.
EDIT: 2 Alright so after reading the comments. I edited my code to this:
#include <iostream>
int main()
{
using namespace std;
char sentence[2000];
for (int i = 0; i < 2000; i++) {
char ch;
cin >> ch;
if (ch != '\n') sentence[i] = ch;
else break;
}
for (int i = 0; i <= 2000; i++) {
cout << sentence[i];
}
return 0;
}
What is expected: The sentence just entered gets outputted back when hitting the enter key.
What happens: The cursor goes to the next line asking for more input.
EDIT: 3 I changed the 2000 to 5 and noticed the behavior. The problem is that the char declaration for ch doesn't detect anything like whitespaces or newlines and therefore the program will only output once 'i' has cycled through fully and we exit the for loop. However I do not know how to fix this. How do I detect the white spaces and newlines?
Solution
You can change it (here). Try this:
#include<iostream>
using namespace std;
int main(int argc, char * argv[])
{
char sentence[2000];
char ch;
for (int i = 0; i < 2000; i++) {
cin >> noskipws >> ch;
if (ch != '\n') sentence[i] = ch;
else {
sentence[i] = '\0';
break;
}
}
for (int i = 0; sentence[i]; i++) {
cout << sentence[i];
}
return 0;
}
The noskipws method of stream manipulators in C++ is used to clear the showbase format flag for the specified str stream. This flag reads the whitespaces in the input stream before the first non-whitespace character.
Answered By - Moshiur Rahman Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.