c++简单的输入处理(由空格分隔的两个字符数组)



我的问题是,我试图输入未知数量的对:- pair的第一个元素是一个单词(我不能使用字符串,只能使用字符和char*[])-然后有一个空间-第二个单词(也不允许字符串)然后是新的行号

如果不使用字符串,我怎样才能最有效地输入这两个单词?在while(!cin.eof())回路里放什么?

从这里开始。如果我是你,我会通读IO的所有常见问题解答。这似乎是一个简单的家庭作业,可以通过几种方式完成,但我认为最好是给你指导,而不是帮你做作业。http://www.parashift.com/c++-faq/input-output.htmlhttp://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 ''
        *secondWord = new char[(end-word) + 1]; // +1 for ''
        strncpy(*firstWord, input, word-input);
        strncpy(*secondWord, word+1, end-word);
        (*firstWord)[word-input] = '';
        (*secondWord)[end-word] = '';
    }
    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;
}

相关内容

  • 没有找到相关文章

最新更新