c++简单的输入处理(由空格分隔的两个字符数组)
c++ simple input handling (2 arrays of chars separated by a space)
我的问题是,我试图输入未知数量的对:- 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;
}
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?