我的问题是,我正在尝试输入未知数量的对: - 一对中的第一个元素是一个单词(我不能使用字符串,只能使用字符和char * []) 然后有一个空间 - 第二个字(也不允许字符串) 然后有新的线路标志
不使用字符串,我怎样才能最有效地输入这两个字?放在while(!cin.eof())
循环中的内容是什么?
答案 0 :(得分:0)
从这里开始。如果我是你,我会通读所有关于IO的常见问题解答。它似乎是一个简单的家庭作业,可以通过多种方式完成,但我认为最好给你指导而不是为你做功课。 http://www.parashift.com/c++-faq/input-output.html http://www.parashift.com/c++-faq/istream-and-eof.html
答案 1 :(得分:0)
看看这对你有用......
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
/* Read a string, split it into two sub-strings with space as the delimiter
return true if split succeeded otherwise return false
sample execution:
input: abc def
output: *firstWord = abc *secondWord = def
return value: true
input: abc def ghi
output: *firstWord = abc, *secondWord = def ghi
return value: true
input: abc
output: *firstWord = undefined, *secondWord = undefined
return value: false
*/
bool readLineAndSplit(char* input, char** firstWord, char** secondWord)
{
if (*firstWord)
delete [] *firstWord;
if (*secondWord)
delete [] *secondWord;
int len = strlen(input);
if (!len)
return false;
// pointer to last character in the input
char* end = input + len - 1; // last character in input
// read first word, scan until a space is encountered
char* word = input;
while(*word != ' ' && word < end )
{
word++;
}
// error: no spaces
if (word == end)
{
cout << input << " isn't valid! No spaces found!" <<endl;
return false;
}
else
{
*firstWord = new char[(word-input) + 1]; // +1 for '\0'
*secondWord = new char[(end-word) + 1]; // +1 for '\0'
strncpy(*firstWord, input, word-input);
strncpy(*secondWord, word+1, end-word);
(*firstWord)[word-input] = '\0';
(*secondWord)[end-word] = '\0';
}
return true;
}
int main()
{
char input[1024];
while (true)
{
cin.getline(input, 1024);
if (strlen(input) == 0)
break;
else
{
char* firstWord = NULL, *secondWord = NULL;
if (readLineAndSplit(input, &firstWord, &secondWord))
{
cout << "First Word = " << firstWord << " Second Word = " << secondWord << endl;
}
else
{
cout << "Error: " << input << " can't be split!" << endl;
break;
}
}
}
return 0;
}