入门级<iostream>地狱(p)
Entry level <iostream> hell(p)
我在使用这段代码时遇到了一些问题。我正在尝试编写一个函数,允许用户输入一个字符串(由多个单词组成),然后返回第一个单词。用Python做一个简单的任务,但C++又让我大吃一惊。我已经完成了一部分,并意识到我仍然需要添加第一个令牌的实现,但在增量调试中,我遇到了一些障碍。我想问的问题是:
- 为什么当我输入整数时,函数会在控制台上打印这些整数?输入int不是应该导致cin流失败,从而重新为用户输入另一个条目吗
- 在返回之前,我如何让窗口暂停(可能等待用户的"输入")?它打印和返回速度如此之快,以至于很难看到它在做什么
这是代码:
/*
* 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;
}
-
因为字符串完全能够容纳"12345"。为什么会失败?
-
我会说
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");
相关文章:
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 双缓冲的waveoutwrite()像地狱一样口吃
- C 字符串比较“祝您好运”&gt;“再见”
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- C 操作员&gt;&gt;与突变器过载
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 是否需要使用 - &gt;运算符在C 中调用成员函数时
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- 错误c++visual studio c2227左侧'->;Init';必须指向类/结构/联合/泛型类型
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- ``这个''不能用this-&gt;指针变量
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 使用shared_ptr<字符串>转换为一个无序集合<字符串>
- 复制/调试一些多线程地狱