我正在尝试创建一个程序来解决倒计时文字游戏,其中涉及询问元音和辅音的比例。我想将随机字符添加到将传递给排列函数的字符串中。
当我运行以下程序并选择“C”时,出现错误“l 缓冲区太小 && 0 c”,并且程序崩溃。
输入“V”将给出错误“Invalid!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;
}
最佳答案
scanf_s
如果您输入换行符,将会读取换行符。在%c
之前添加一个空格让函数跳过它们。- 您对
strcat_s
的使用情况看起来很奇怪。该函数将采用三个参数,但您只传递两个参数。在这种情况下,您只需分配字符即可。 -
#include <string>
和using namespace std;
适用于 C++,而不是 C,这里不使用它们。删除它们。 - 您的类型
main()
看起来很奇怪。
试试这个(抱歉,我讨厌 VC++ 特定的函数):
#include <stdio.h>
int main(void) {
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(" %c", &type);
if (type == 'V')
for (k = 0; k<1; k++) {
v = (rand() % 5);
letters[i] = vowels[v];
}
if (type == 'C')
for (l = 0; l<1; l++) {
c = (rand() % 21);
letters[i] = consonants[c];
}
else
printf("Invalid!");
break;
}
printf("%s", letters);
return 0;
}
关于c - 如何将随机生成的字符添加到 C 中的字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36602856/