我编写了一个程序,接受一个名为source
的字符串。然后它可以接受另一个名为insertion
的字符串。然后,用户会选择position
中source
他们想要插入insertion
的{{1}}。然后打印回结果。
当我输入"the young son"
之类的字符串时,程序运行得非常好。我可以在[^\n]
的{{1}}函数中添加scanf
。
如果我然后使用常规source[]
输入"per"
并选择将其放在scanf
,那么我会得到很好的打印position = 10
。
但是,如果我选择插入一个空格,例如"the young person"
放入"fat "
,希望完成"the cat"
,那么它会忽略该空格正常进行并将它们捆绑在一起。
或者,如果我将[{1}}添加到"the fat cat"
进行插入,它实际上决定取消之前的内容,它甚至不让我输入[^\n]
,它只需使用scanf
和insertion
,并假设它们是分开的。
有什么方法吗?
请记住,这是一个学习练习(我已经通过了标准,这只是我的挑剔),除了"the"
和{"cat"
之外我不允许使用任何库函数{1}}。我也无法使用任何指针语法,因为它还没有被覆盖,我不想跳过。
谢谢!
以下是我的代码:
printf
答案 0 :(得分:0)
基本问题是scanf("%[^\n]",
...读取但 NOT 包括换行符。因此换行仍在等待输入以便稍后扫描读取。这意味着第二个调用不会读取任何内容(下一个字符仍然是换行符,因此它会立即停止并失败。)
所以你需要阅读并丢弃换行符。 scanf("%*c");
或scanf("%*1[\n]");
可以做到这一点。
另一个问题是你没有检查scanf的返回值,也没有限制输入以避免字符串溢出。你可以这样做:
if (scanf("%39[^\n]%*1[\n]", source) < 1) {
printf("There was a problem!\n");
exit(1); }
答案 1 :(得分:0)
考虑使用fgets进行输入并使用sscanf解析整数。需要包含源数组的大小以避免写入太多字符。可以使用一对指针迭代insertString
中的数组。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 256
void insertString(char source[], int size, char insertion[], int position);
int stringLength(const char string[]);
int main(void)
{
int position;
int result = 0;
char source[SIZE];
char insertion[SIZE];
char input[SIZE];
printf("What's your first string?\n");
if ( ( fgets( source, sizeof ( source), stdin)) == NULL) {
printf ( "could not get input\n");
return 1;
}
source[strcspn ( source, "\n")] = '\0';//remove newline
printf("What do you want to insert?\n");
if ( ( fgets( insertion, sizeof ( insertion), stdin)) == NULL) {
printf ( "could not get input\n");
return 1;
}
insertion[strcspn ( insertion, "\n")] = '\0';//remove newline
do {
printf("Where do you want to put it?\n");
if ( ( fgets( input, sizeof ( input), stdin)) == NULL) {
printf ( "could not get input\n");
return 1;
}
result = sscanf(input, "%d", &position);
} while ( result != 1 || position < 0);//loop on bad input
insertString(source, sizeof ( source), insertion, position);
printf("Here's the result: %s\n", source);
return 0;
}
void insertString(char source[], int size, char insertion[], int position)
{
char *to = NULL, *from =NULL;
// Find length of string
int lengthBig = stringLength(source);
int lengthSmall = stringLength(insertion);
int lengthTotal = (lengthBig + lengthSmall);
if ( lengthTotal >= size) {
printf ( "not enough space\n");
return;
}
if ( position > lengthBig) {
position = lengthBig;
}
//shift to make room for insertion
to = &source[lengthTotal + 1];
from = &source[lengthBig + 1];
while(from != &source[position])//loop back to source[position]
{
*to = *from;
to--;
from--;
}
*to = *from;
//put insertion into source
to = &source[position];
from = insertion;
while(*from)//loop until '\0'
{
*to = *from;
to++;
from++;
}
}
int stringLength(const char string[])
{
int count =0;
while(*string) {
count++;
string++;
}
return count;
}