2014-09-10 84 views
0


我读的C++底漆第五,我有一个小问题,一个练习:
C++使用问题CIN和CTRL + Z

阅读从CIN的词序列和存储的值的矢量。在 之后,您已阅读所有单词,处理矢量并将每个单词更改为 大写。打印变形的元素,八个字到一行。

我的代码是这样的:

#include <iostream> 
#include <vector> 
#include <string> 
#include <cctype> 

using std::vector; 
using std::string; 
using std::cin; 
using std::cout; 
using std::endl; 

int main(){ 

    vector<string> words; 
    string wordBuffer; 
    vector<string> output(1); 

    while (cin >> wordBuffer){ 
     words.push_back(wordBuffer); 
    } 

    for (string &word : words){ 
     for (char &letter : word){ 
      letter = toupper(letter); 
     } 
    } 

    unsigned currentLine = 0; 
    for (decltype(words.size())index = 0; index < words.size(); ++index){ 

     output[currentLine] += words[index] + " "; 

     if ((index+1) % 8 == 0){ 
      ++currentLine; 
      output.push_back(""); 
     } 

    } 

    for (string s : output){ 
     s[s.size() - 1] = 0; //removing the whitespace 
     cout << s << endl; 
    } 

    system("pause"); 
    return 0; 
} 

现在,一切正常,但我有一个问题,用的话通过控制台输入。
如果我写

我写一个随机单词^ Z

,然后按Enter键没有任何反应。我不得不重新改写^ Z我已经按下后输入,喜欢这里:

我写一个随机单词
^ Z

你能expain我为什么?谢谢!

PS:我在说,因为在我以前的程序中,在同一行中编写^ Z可以正常工作。像这样的代码:

#include <iostream>; 


int main(){ 
    int currval = 0,val = 0; 

     int count = 1; 
     while (std::cin >> val){ 
      if (currval == val){ 
       ++count; 
      } 
      else { 
       std::cout << "The number " << currval << " appears " << count << " times" << std::endl; 
       currval = val; 
       count = 1; 
      } 
     } 
     std::cout << "The number " << currval << " appears " << count << " times" << std::endl; 

    system("pause"); 

    return 0; 
} 

我想不通为什么:(

+0

你是写^ Z还是按Ctrl + Z? (在另一个程序中) – 2014-09-10 13:33:47

+0

这不是C++问题,而是Windows中的标准行为。为了确认你可以运行这个简单的程序并获得相同的行为(CTRL + Z必须在它自己的行上按下才能终止):'char c; while((c = getchar())!= EOF)putchar(c);' – Brandin 2014-09-10 13:35:43

回答

3

^Z必须是第一个,以便Windows将其视为Ctrl + Z,否则它只是被视为无意义的字符。

如果你想它的工作就像你写我建议:

String wordBuffer("") 
while (strcmp(wordBuffer[strlen(wordBuffer)-3], "^Z") != 0){ 
    words.push_back(wordBuffer); 
    cin >> wordBuffer 
} 

编辑:在你的第二个例子是可行的,因为当你的C++知道要数给定的字符串分割读整数在空间(或ENTER如果数字在每一行分别输入)分别读取每一个数字,所以如果你输入:

123 2323 4545 43 ^Z 

它会读取123,然后2323,...然后^ Z,所以它会像在一个单独的行中得到它,但是当你读取字符串,它不能这样做,因为一个字符串包含每个符号,所以它分开输入在按下,并且为什么第二个工作

+0

为什么在我的第二个例子中它有效?这是我无法理解的事 – 2014-09-10 13:56:17

+0

我编辑了我的答案,现在应该清楚了 – 2014-09-10 14:02:59

+0

谢谢!现在一切都很清楚! – 2014-09-10 14:45:19

0

据我所知按Ctrl +ž放置在键盘缓冲区的任何其他进入前的符号。因此,任何Ctrl键之前输入的字符 + ž将被丢弃。你需要做以下

I am writing a random words ENTER 
^Z ENTER