better understanding of getline() and cin - c++

Trying to get some basic understanding of console functionalities. I am having issues so consider the following...
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
/*
This is a template Project
*/
void MultiplicationTable(int x);
int main()
{
int value = 0;
printf("Please enter any number \n\n");
getline(cin, value);
MultiplicationTable(value);
getchar();
return 0;
}
I actually based this off code from http://www.cplusplus.com/doc/tutorial/basic_io/ . My IDE is not recognizing getline() so of course when I compile the application. I get an error
'getline': identifier not found
Now take a look at this code
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
/*
This is a template Project
*/
void MultiplicationTable(int x);
int main()
{
int value = 0;
printf("Please enter any number \n\n");
cin>>value;
MultiplicationTable(value);
getchar();
return 0;
}
When I execute this line of code the console window opens and immediately closes. I think I a missing something about cin. I do know that it delimits spaces but I don't know what else. what should I use for input to make my life easier.

The function getline() is declared in the string header. So, you have to add #include <string>.
It is defined as istream& getline ( istream& is, string& str );, but you call it with an int instead of a string object.
About your second question:
When I execute this line of code the console window opens and immediately closes
There is probably still a '\n' character from your input in the stream, when your program reaches the function getchar() (which I assume you put there so your window doesn't close). You have to flush your stream. An easy fix is, instead of getchar(), add the line
int c;
while((c = getchar()) != '\n'){}
This will flush your stream until the next line-break.
Remark: conio.h is not part of the c++ standard and obsolete.

The getline function reads strings, not integers:
#include <string>
#include <iostream>
using namespace std;
int main() {
string line;
getline( cin, line );
cout << "You entered: " << line << endl;
}

You are exiting the program before you can view the results because (I'm guessing) you double-clicked the .exe file from inside a Windows Explorer (or the Desktop) view in order to execute. Instead, go to Start, Run, type in cmd.exe and open a command window. Navigate to where your program resides. Type in your program's name on the command line and execute. It will stay open until you intentionally close the command window.

Related

Avoiding Tab Line Change

When you write input in C++, you verify that the input is over by pressing enter, sadly that also changes the line.
But I still want to output something in that particular line.
How can I stay there? Is there a way to change how you confirm the end of the input?
I'm using the Cygwin64 Terminal
You can use getline.
#include <iostream>
int main() {
std::string str;
std::getline(std::cin, str, '.');
std::cout << str;
return 0;
}
Input
abcd.efgh
Output
abcd
Now '.' is an end of input.
getline Reference.
A simple getline() could be used. getline() takes in a delimiter character which can be utilized to "change how you confirm the end of the input". Without that parameter, the default delimiter is \n.
#include <iostream>
using namespace std;
int main()
{
string x;
getline(cin, x, 'm');
cout << x;
}
Input: test1test2mtest3
Output: test1test2
Special characters can also be used, like \t:
#include <iostream>
using namespace std;
int main()
{
string x;
getline(cin, x, '\t');
cout << x;
}
Input:
test1
test2
test3
Output:
test1
test2
A downside that it would still requires users to press Enter to complete the input, as shown above. Because, as #Öö Tiib pointed out:
C++ standard I/O streams are just that ... streams. The C++ is not
addressing from where these come and to where go.
In other words, generally C++ can't control the terminal input/output system, it only knows if something is inputted or if something should be outputted, and feed that to the terminal.
Info : https://en.cppreference.com/w/cpp/string/basic_string/getline

How can I make sure the program stops running after the IDE has output result

I'm new to C++. I have run the code before in NetBeans. However, after I have entered a string and IDE has output the result, I was expecting the program to stop running.
However, there is a bar at the bottom of the NetBeans IDE that indicates the program is still running.
Why is this happening?
What change should I make to my code so that the program will stop running?
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Enter a string of characters including punctuation." << endl;
for (string s; getline(cin, s); cout << endl)
for (auto i : s)
if (!ispunct(i)) cout << i;
return 0;
}
The program looped back to getline as you told it to with the for statement. Your exit condition is getline returns false. To do this you need to close the file, you do this by entering Control-D on Unix or Control-Z on Windows.
Another tactic would be to loop until somebody types 'q' or 'exit' or an empty line.

Read line in C++ till EOF

I'm writing a function that reads line by line from cin and returns when it sees ; character.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
int read_cmd(char *cmd)
{
cout << "Please enter a string: \n";
cmd[0]='\0';
while(1){
char currentLine[10000];
currentLine[0]='\0';
cin.getline(currentLine,10000);
if (strcmp(currentLine,";")==0){
break;
}
strcat(cmd, "\n");
strcat(cmd, currentLine);
}
return 0;
}
int main(){
char cmd[1000];
while (1){
read_cmd(cmd);
cout<< cmd << endl;
}
}
I then tested it using text fed from another file via pipe.
./read_cmd < test_file
contents of test_file:
line 1
line 2
;
This outputs results just fine, however it gives me a segmentation fault at the end. Is there a way for cin to check if it's coming across an EOF and terminates?
To detect the EOF you should use something like:
while (cin.good() && !cin.eof())
{
// Read the file
}
See the documentation for cin, in particular the good() (for error checking) and eof() member functions.
In particular this example might be helpful.
I would highly suggest the use of the string object for something like this, that way you're not wasting space, as well as ensuring that you have enouch space. You can also do it without a loop.
string currentLine;
getline(cin, currentLine, ';');
Now, if you need to get just the last line with has the semi-colon, a loop is necessary, but still you can do it at little more easily.
string currentLine;
while(getline(cin, currentLine)){
if(currentLine.find(";") != string::npos){
break;
}
}
Use strings to pass things around as well. There's always the .clear() method as well that any string has for easy emptying.
string getline
string Object

Why isn't my program displaying the integer I'm outputting?

#include<iostream>
#include<string>
using namespace std;
int main()
{
int i;
cout<<"enter ur no. plz";
cin>>i;
cout<<"ur no. is:"<<i;
cin.get();
return 0;
}
This code is not displaying the integer I entered. It returns back after entering an integer and hitting enter. I am using dev C++.
After the user enters the integer, there is still a newline character left in the input buffer. cin.get() reads that character, then the program immediately ends. You could put an additional call to get if you want the program to stay open. Or, before the call to get, you could have a call to ignore:
std::cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
That would clear the newline character from the buffer.
Or you could run your program from the command line, you'll see the output then.
Add some endls:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i;
cout<<"enter ur no. plz"<<endl;
cin>>i;
cout<<"ur no. is:"<<i<<endl;
cin.get();
return 0;
}

Reading a full line of input

I'm trying to store the input that user enters through console. so I need to include the "enter" and any white space.
But cin stops giving me input after the first space.
Is there a way to read whole lines until CTRL+Z is pressed, or something?
is there a way like readLines till CTRL+Z is pressed or something ??
Yes, precisely like this, using the free std::getline function (not the istream method of the same name!):
string line;
while (getline(cin, line)) {
// do something with the line
}
This will read lines (including whitespace, but without ending newline) from the input until either the end of input is reached or cin signals an error.
#include <iostream>
#include <string>
using namespace std;
int main()
string s;
while( getline( cin, s ) ) {
// do something with s
}
}
For my program, I wrote the following bit of code that reads every single character of input until ctrl+x is pressed. Here's the code:
char a;
string b;
while (a != 24)
{
cin.get(a);
b=b+a;
}
cout << b;
For Ctrl+z, enter this:
char a;
string b;
while (a != 26)
{
cin.get(a);
b=b+a;
}
cout << b;
I can't confirm that the ctr+z solution works, as I'm on a UNIX machine, and ctrl+z kills the program. It may or may not work for windows, however; You'd have to see for yourself.
#include <string>
#include <iostream>
int main()
{
std::cout << "enter your name: ";
std::string name;
std::getline(std::cin, name);
return 0;
}
You can use the getline function in c++
#include<iostream>
using namespace std;
int main()
{
char msg[100];
cin.getline(msg,100);
return 0;
}