相关疑难解决方法(0)

为什么std :: getline()在格式化提取后会跳过输入?

我有以下代码提示用户输入他们的名字和状态:

#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 "
Run Code Online (Sandbox Code Playgroud)

为什么输出中省略了状态名称?我给出了正确的输入,但代码忽略了它.为什么会这样?

c++ iostream input c++-faq istream

92
推荐指数
2
解决办法
2万
查看次数

C++ Noobie - 为什么移动这些行会破坏我的应用程序?

这是我第一次尝试使用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 …
Run Code Online (Sandbox Code Playgroud)

c++

4
推荐指数
1
解决办法
165
查看次数

为什么跳过std :: getline()?

我有这个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" …
Run Code Online (Sandbox Code Playgroud)

c++

3
推荐指数
1
解决办法
8219
查看次数

如果不存在,为什么 getline 返回空行

我有一个包含以下几行的文件:

5556
0   bla.dxf
1   blub.dxf
2   buzz.dxf
Run Code Online (Sandbox Code Playgroud)

数字和文本分别用单数制表符分隔,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;
}
Run Code Online (Sandbox Code Playgroud)

当我解析文件时,我得到一个空行,尽管显然没有。输出内容如下:

5556
String was empty
0   bla.dxf
1   blub.dxf
2   buzz.dxf
Run Code Online (Sandbox Code Playgroud)

这只是一个最小的例子。整个文件和解析器更复杂,我非常想对第一个元素使用直接解析,对其余元素使用 getline。我对行解析有什么误解getline以及如何避免获得空行?

c++ string io

0
推荐指数
1
解决办法
6880
查看次数

标签 统计

c++ ×4

c++-faq ×1

input ×1

io ×1

iostream ×1

istream ×1

string ×1