我写了一个程序,接受一个名为source
的字符串。然后它可以接受另一个字符串insertion
。然后用户选择source
中的哪个position
他们想要插入insertion
。然后打印结果。为什么我不能输入两个空格字符串?
当我输入字符串如"the young son"
时,程序运行的很好。我可以简单地在scanf
函数中为source[]
添加[^\n]
。
如果我再输入"per"
使用常规scanf
,并选择将其放置在position = 10
,然后我得到了一个很好打印出来"the young person"
。
但是,如果我选择有一个空间的插入,如"fat "
投入"the cat"
,希望完成"the fat cat"
,那么它会如果我一起正常进行,并帮它忽略的空间。
,或者,如果我添加[^\n]
到scanf
插入过,它实际上决定取消了以前的,它甚至没有让我输入一个insertion
,它只是使用"the"
和"cat"
,并假定它们是独立的。
有没有办法解决这个问题?
请记住,这是一个学习练习(我已经通过了这个标准,这只是我的挑剔),其中我不允许使用printf
和scanf
以外的任何库函数。我也无法使用任何指针语法,因为它尚未被覆盖,我不想跳过。
谢谢!
这里是我下面的代码:
#include <stdio.h>
void insertString(char source[], char insertion[], int position);
int stringLength(const char string[]);
int main(void)
{
int position;
char source[40];
char insertion[40];
printf("What's your first string?\n");
scanf("%[^\n]s", source);
printf("What do you want to insert?\n");
scanf("%[^\n]s", insertion);
printf("Where do you wanna put it?\n");
scanf("%i", &position); //
// call function
insertString(source, insertion, position);
// print out result, stored in source
printf("Here's the result: %s\n", source);
return 0;
}
void insertString(char source[], char insertion[], int position)
{
int i, j;
// Find length of string
int lengthBig = stringLength(source);
int lengthSmall = stringLength(insertion);
int lengthTotal = (lengthBig + lengthSmall) -1;
// move up source characters after position
for(i = lengthBig - 1; i >= position; i--)
{
source[i + (lengthSmall) ] = source[i];
}
// move in insertion characters
for(j = lengthSmall-1; j >= 0; j--)
{
source[position + j] = insertion[j];
}
// add null character
source[lengthTotal + 1] = '\0';
}
int stringLength(const char string[])
{
int count =0;
while(string[count] != '\0')
count++;
return count;
}
' “%[^ \ n]的”' - >' “%39 [^ \ n]的%* C”' – BLUEPIXY
忘记你听说过scanf'的',并以'fgets'代替(或者,如果你有,getline);这是前两次对'scanf'的调用的替代方案;第三,你还需要'strtol'。 – zwol