better understanding of getline() and cin

2019-06-09 10:29发布

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.

3条回答
叼着烟拽天下
2楼-- · 2019-06-09 11:10

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;
}
查看更多
祖国的老花朵
3楼-- · 2019-06-09 11:18

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.

查看更多
狗以群分
4楼-- · 2019-06-09 11:20

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.

查看更多
登录 后发表回答