我一直在使用 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/