我正在尝试创建一个解决倒计时单词游戏的程序,该游戏涉及要求一定比例的元音和辅音。我想将随机字符添加到将传递给置换函数的字符串中。
当我运行以下程序并选择“C”时,我收到错误“l buffer is too small&& 0 c”,程序崩溃。
键入“V”会出现错误“无效!EIOU”而不会崩溃。
如何创建这个随机字符串,其元音和辅音数量由用户的输入决定?
这应该作为数组来完成吗?
// April16Assignment.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
#include <string>
using namespace std;
const char * main() {
char type, letters[10] = { };
char vowels[6] = { 'A', 'E', 'I', 'O', 'U' };
char consonants[21] = { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z' };
int i, k, v, l, c;
for (i = 0; i < 9; i++) {
printf("Vowel or consonant? (V/C)\n");
scanf_s("%c", &type);
if (type == 'V')
for (k = 0; k<1; k++) {
v = (rand() % 5);
strcat_s(letters, &vowels[v]);
}
if (type == 'C')
for (l = 0; l<1; l++) {
c = (rand() % 21);
strcat_s(letters, &consonants[c]);
}
else
printf("Invalid!");
break;
}
printf("%s", letters);
return letters;
}
答案 0 :(得分:1)
cat test.txt
one~|~two~|~three~|~four~|~five~|~six~|~seven~|~eight~|~nine~|~ten1234562one~|~2two~|~2three~|~2four~|~2five~|~2six~|~2seven~|~2eight~|~2nine~|~2ten1234563one~|~3two~|~3three~|~3four~|~3five~|~3six~|~3seven~|~3eight~|~3nine~|~3ten123456
sed -e's/\(\([^~|~]*~|~\)\{9\}[^~|~]*\)~|~/\1\n/g' test.txt
one~|~two~|~three~|~four~|~five~|~six~|~seven~|~eight~|~nine~|~ten1234562one
2two~|~2three~|~2four~|~2five~|~2six~|~2seven~|~2eight~|~2nine~|~2ten1234563one~|~3two
3three~|~3four~|~3five~|~3six~|~3seven~|~3eight~|~3nine~|~3ten123456
将会读取换行符。在 one~|~two~|~three~|~four~|~five~|~six~|~seven~|~eight~|~nine~|~ten123456
2one~|~2two~|~2three~|~2four~|~2five~|~2six~|~2seven~|~2eight~|~2nine~|~2ten123456
63one~|~3two~|~3three~|~3four~|~3five~|~3six~|~3seven~|~3eight~|~3nine~|~3ten123456
之前添加空格,以使该功能跳过它们。scanf_s
的使用似乎很奇怪。该函数将采用三个参数,但您只传递两个参数。在这种情况下,您只需指定字符。%c
和strcat_s
适用于C ++,而非C,并且此处不使用它们。删除它们。#include <string>
的类型看起来很奇怪。试试这个(对不起,我讨厌VC ++特定的功能):
using namespace std;