getline()只读第二个单词(bug)

时间:2015-07-06 21:46:01

标签: c++

我正在尝试创建一个读取名称并将其打印出来的程序。我想使用cin所以它将读取整行,因此名称中可以包含任意数量的单词。 (这就是为什么我不想只使用Rock Lee两次。)但它只打印第二个单词。这有什么问题?

输入:Lee

输出:#include <iostream> #include <iomanip> #include <string> using namespace std; int main () { string name; cout << "Enter your name: "; cout.flush(); cin >> name; getline(cin, name, '\n'); if (name == "") { cout << "Name is blank."; return -1; } cout << name; return 0; }

  'pulling in reader from xml'

  Dim clientReader As XmlReader = XmlReader.Create("launch.xml")

    'Read the XML files to determine the server version'

    clientReader.ReadToFollowing("serverURL")
    Dim serverURL As String = clientReader.ReadElementContentAsString()
    Dim serverXMLpath As String = serverURL & "Updater/serverInfo.xml"
    Dim serverReader As XmlTextReader = New XmlTextReader(serverXMLpath)
    serverReader.ReadToFollowing("serverVer")
    Dim serverVer As Double = serverReader.ReadElementContentAsDouble()

    'Read client XML to determine clientVersion'
    clientReader.ReadToFollowing("clientVer")
    Dim clientVer As Double = clientReader.ReadElementContentAsDouble()

    'Determine what updates need to be downloaded'

    serverReader.ReadToFollowing("totalUpdates")
    Dim totalUpdates As Integer = serverReader.ReadElementContentAsInt()

    '.....'
    'files are downloaded and updated here'
    '.....'


    clientReader.Close()
    serverReader.Close()


    'change the client version!'
    Dim clientWriter As New XmlTextWriter("launch.xml", System.Text.Encoding.UTF8)
    'clientWriter.WriteElementString("clientVer", serverVer)

1 个答案:

答案 0 :(得分:2)

cin >> name;

从输入流中读取“Rock”并将其保存在name中。该流现在包含“Lee \ n”。现在

getline(cin, name, '\n');

从流中读取剩余的“Lee \ n”,丢弃\n,然后用结果覆盖namename现在包含“Lee”。

要将整行读入name,请移除“窃取”第一个字的cin行。

顺便说一下,cout.flush();是没有必要的,因为coutcin默认绑定,即当控件到达cout时,cin将始终被刷新