我的問題是,我試圖輸入未知數量的對: - 一對中的第一個元素是一個詞(我不能使用字符串,只有字符與char * []) - 那麼有一個空間 -the第二字(字符串也不允許) 再有就是新行符號C++簡單的輸入處理(2個由空格分隔的字符數組)
在不使用字符串,哪能最有效地輸入這兩個話?什麼放在while(!cin.eof())
循環?
我的問題是,我試圖輸入未知數量的對: - 一對中的第一個元素是一個詞(我不能使用字符串,只有字符與char * []) - 那麼有一個空間 -the第二字(字符串也不允許) 再有就是新行符號C++簡單的輸入處理(2個由空格分隔的字符數組)
在不使用字符串,哪能最有效地輸入這兩個話?什麼放在while(!cin.eof())
循環?
從這裏開始。如果我是你,我會閱讀關於IO的所有常見問題。這似乎是一個簡單的作業任務,可以通過幾種方式完成,但我認爲最好是給你指導而不是爲你做功課。 http://www.parashift.com/c++-faq/input-output.html http://www.parashift.com/c++-faq/istream-and-eof.html
看看這個作品你...
#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;
}
@KerrekSB感謝 – Simon