我有以下代码提示用户输入他们的名字和状态:
#include <iostream>
#include <string>
int main()
{
    std::string name;
    std::string state;
    if (std::cin >> name && std::getline(std::cin, state))
    {
        std::cout << "Your name is " << name << " and you live in " << state;
    }
}
我发现该名称已被成功提取,但不是州.这是输入和结果输出:
Run Code Online (Sandbox Code Playgroud)Input: "John" "New Hampshire" Output: "Your name is John and you live in "
为什么输出中省略了状态名称?我给出了正确的输入,但代码忽略了它.为什么会这样?
这是我第一次尝试使用C++,下面是一个通过控制台应用程序计算提示的示例.完整(工作代码)如下所示:
// Week1.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    // Declare variables
    double totalBill = 0.0;
    double liquour = 0.0;
    double tipPercentage = 0.0;
    double totalNoLiquour = 0.0;
    double tip = 0.0;
    string hadLiquour;
    // Capture inputs
    cout << "Did you drink any booze? (Yes or No)\t";
    getline(cin, hadLiquour, '\n');
    if(hadLiquour == "Yes") {
        cout << "Please enter you booze bill\t";
        cin …我有这个C ++简单程序;
#include <iostream>
using std::endl;
using std::cout;
using std::cin;
using std::getline;
#include <string>
using std::string;
struct Repository
{
    string name;
    string path;
    string type;
    string command;
};
int main()
{
    Repository rp;
    cout << "\nEnter repo name: ";
    cin >> rp.name;
    cout << "Enter repo path: ";
    cin >> rp.path;
    cout << "Enter repo type: ";
    cin >> rp.type;
    cout << "Enter repo command: ";
    getline(cin, rp.command);
    cout << "\nRepository information: " << endl;
    cout << rp.name << "\n" …我有一个包含以下几行的文件:
5556
0   bla.dxf
1   blub.dxf
2   buzz.dxf
数字和文本分别用单数制表符分隔,5556后没有空格字符。以下代码用于解析。
int main(int, char**){
  std::ifstream file("test.bld");
  std::string buildingName;
  file >> buildingName;
  std::cout << buildingName << std::endl;
  std::string buf;
  while(getline(file, buf)) {
    if(buf.empty()){std::cout << "String was empty"<<std::endl;}
    else std::cout << buf << std::endl;
  }
  return 0;
}
当我解析文件时,我得到一个空行,尽管显然没有。输出内容如下:
5556
String was empty
0   bla.dxf
1   blub.dxf
2   buzz.dxf
这只是一个最小的例子。整个文件和解析器更复杂,我非常想对第一个元素使用直接解析,对其余元素使用 getline。我对行解析有什么误解getline以及如何避免获得空行?