入门级<iostream>地狱(p)

Entry level <iostream> hell(p)

本文关键字:地狱 gt iostream lt      更新时间:2023-10-16

我在使用这段代码时遇到了一些问题。我正在尝试编写一个函数,允许用户输入一个字符串(由多个单词组成),然后返回第一个单词。用Python做一个简单的任务,但C++又让我大吃一惊。我已经完成了一部分,并意识到我仍然需要添加第一个令牌的实现,但在增量调试中,我遇到了一些障碍。我想问的问题是:

  1. 为什么当我输入整数时,函数会在控制台上打印这些整数?输入int不是应该导致cin流失败,从而重新为用户输入另一个条目吗
  2. 在返回之前,我如何让窗口暂停(可能等待用户的"输入")?它打印和返回速度如此之快,以至于很难看到它在做什么

这是代码:

/*
* Problem 1: "Extract First String"
* Takes a user string and extracts first token (first token can be a whole word)
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void ExtractFirstToken();
int main()
{
    ExtractFirstToken();
    return 0;
}
/*
* Trying to create a function that will allow a user to enter a string of words and
* then return the first word
*/
void ExtractFirstToken()
{
    cout << "Please enter a string (can be multiple words): ";
    string stringIn;
    while (true)
    {
        cin >> stringIn;
        if (!cin.fail()) break;
        cin.clear();
        cout << "not a string, please try again: ";
    }
    cout << stringIn;
}
  1. 因为字符串完全能够容纳"12345"。为什么会失败?

  2. 我会说std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'n'); 之类的话(嘿,有趣的是,我的答案和Benjamin Lindley的完全一样,一直到使用numeric_limits和streamsize)

这将等待输入,直到您按下回车键。

1)不。数字作为字符串是完全有效的。

首先编写一个函数,根据您的定义确定字符串是否为单词。类似这样的东西:

bool IsWord(const std::string & str)
{
    return str.find_first_of("0123456789 tn") == std::string::npos;
}

然后:

std::string word;
while(std::cin >> word)
{
    if (IsWord(word)) break;
    cout << "not a word, please try again: ";
}
std::cout << word;

2) 只需从命令行运行程序即可。

以下是标准格式化的I/O习惯用法:

#include <iostream>
#include <sstream>
#include <string>
int main()
{
    std::string line;
    std::cout << "Please enter some text: ";
    while (std::getline(std::cin, line))
    {
        std::istringstream iss(line); 
        std::string word;
        if (iss >> word)
        {
            std::cout << "You said, '" << line << "'. The first word is '" << word << "'.n";
            std::cout << "Please enter some more text, or Ctrl-D to quit: ";
        }
        else
        {
             // error, skipping
        }
    }
}

除了到达输入流的末尾之外,您不能不读取字符串,用户必须用Ctrl-D或类似的信号(MS-DOS上的Ctrl-Z)来发出信号。您可以添加另一个中断条件,例如,如果修剪的、向下转换的输入字符串等于"q"左右

内部循环使用字符串流来标记行。通常,您会处理每个标记(例如,转换为数字?),但这里我们只需要一个,即第一个单词。

所有可打印字符都是有效的字符串元素,包括数字。因此,如果你想将数字解释为无效输入,你就必须自己做这项工作。例如:

if (stringIn.find_first_of("0123456789") != stringIn.npos)
    cout << "not a valid string, please try again: ";

第一部分有很多答案,所以我将帮助完成第二部分:

system("pause");