C++ 无法获取 strtok 的用户输入

标签 c++ input strtok sentence

我一直在使用 C++ 中的这段代码遇到问题:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>

using namespace std;

int main ()
{
   string words[25];
   int i = 0;
   char * word;
   cout << "Input a phrase, no capital letters please.";
   char phrase[100] = "this is a phrase";
   word = strtok (phrase, " ,.");

   while (word != NULL)
   {
      i++;
      words[i] = word;
      cout << words[i] << " ";
      word = strtok (NULL, " ,.-");
      int g = 0;
   }
   cout << endl << endl;

   int g = 0;
   while (g < i)
   {
      g++;
      char f = words[g].at(0);
      if ((f == 'a') || (f == 'e') || (f == 'i') || (f == 'o') || (f == 'u') || (f == 'y'))
      {
         words[g].append("way");
         cout << words[g] << " ";
      }
      else
      {
         words[g].erase (0,1);
         cout << words[g] << f << "ay" << " ";
      }

   }
   cout << endl;
   system("PAUSE");
}

我实际上希望我的程序用户生成要放入 char phrase[100] 中的短语,但我无法找出正确的语法来在不搞砸翻译的情况下启动输入。

这是一个将短语翻译成 pig latin BTW 的程序。

最佳答案

你想要的是:

char phrase[100];
fgets(phrase, 100, stdin);

不过,如评论和其他答案中所述,您在 C++ 中使用 C 字符串函数,这很奇怪。除非作业或其他事情需要,否则您不应该这样做。

改为使用:

string input;
getline(cin, input);

要标记化,您可以执行以下操作:

string token;
size_t spacePos;
...
while(input.size() != 0)
{
    spacePos = input.find(" ");
    if(spacePos != npos)
    {
        token = input.substr(0, spacePos );
        input = input.substr(spacePos  + 1);
    }
    else
    {
        token = input;
        input = "";
    }

    // do token stuff
}

或者,跳过所有爵士乐:

string token;

while(cin >> token)
{
    // Do stuff to token
    // User exits by pressing ctrl + d, or you add something to break (like if(token == "quit") or if(token == "."))
}

关于C++ 无法获取 strtok 的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12737604/

相关文章:

javascript - 如何使 ContentEditable 框的突出显示区域更大?

c - 从命令行打开的 .txt 文件中读取整数

c++ - 我的程序是在调用 'parsePacket()' 后继续还是等到它接收到数据?

bash - 如何将用户输入读入 Bash 中的变量?

c++ - 嵌入式系统的开源视频编码器

c - strtok 指针采用分隔符值

c - 使用 strtok [C] 时获取 Null 值

arrays - strtok 大小 1 的读取无效

c++ - 'if' 表达式后续变量声明

c++ - 在 Qt 中注册 iOS 默认用户首选项