c - 我怎样才能更正我的代码?我的代码的主要目标是从另一个字符串初始化新字符串,只需复制 C 中的 n 个首字母
问题描述
你能给我建议来纠正我的代码吗?它应该从另一个字符串初始化new_string
,并复制该n
字符串的第一个字母。输出应该是字符串。但是我的代码什么也没打印。我该如何解决?
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char str[99];
int n, i, len;
printf("Enter a string:");
scanf("%s", str);
printf("enter n:");
scanf("%i", &n);
if (n > len) {
n = len;
}
char *new_string = malloc(n + 1);
for (int i = 0; i < n; i++) {
new_string[i] = str[i];
}
new_string[i] = '\0';
printf("STring:%s", new_string);
return 0;
}
解决方案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char str[100];
printf("Enter string: ");
/*
* take spaces into account (optional),
* prevent buffer overflow and
* check return value of `scanf`
*/
if (scanf("%99[^\n]", str) != 1) {
fprintf(stderr, "Error: invalid input\n");
return EXIT_FAILURE;
}
int n;
printf("Enter index: ");
/* check return value of `scanf` */
if(scanf("%d", &n) != 1) {
fprintf(stderr, "Error: invalid input\n");
return EXIT_FAILURE;
}
/* initialize `len` */
int len = strlen(str);
if (n > len)
n = len;
char *new_str = malloc(n + 1);
strncpy(new_str, str, n);
printf("New string: %s\n", new_str);
return EXIT_SUCCESS;
}
或者您可以进行以下代码注释中解释的更改:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char str[99];
printf("Enter string: ");
/*
* take spaces into account (optional),
* prevent buffer overflow and
* check return value of `scanf`
*/
if (scanf("%99[^\n]", str) != 1) {
fprintf(stderr, "Error: invalid input\n");
return EXIT_FAILURE;
}
int n;
printf("Enter index: ");
/* check return value of `scanf` */
if(scanf("%d", &n) != 1) {
fprintf(stderr, "Error: invalid input\n");
return EXIT_FAILURE;
}
/* initialize `len` */
int len = strlen(str);
if (n > len)
n = len;
char *new_str = malloc(n + 1);
for (int i = 0; i < n; ++i)
new_str[i] = str[i];
/* you don't need `i` here */
new_str[n + 1]= '\0';
printf("New string: %s\n", new_str);
return EXIT_SUCCESS;
}
推荐阅读
- python - 当风向是分类值时如何绘制风玫瑰图
- flutter - flutter - 在应用程序中使用主题
- amazon-web-services - 将多个域路由到现有 AWS 资源
- flutter - Flutter 中关于 LATLNG 包和 LatLng 类型的问题
- firebase - 被部署在 Firebase Functions 上的快速服务器的 CORS 策略阻止,即使定义了 cors
- python - 从一个视频中重建 Veritasium 的情节
- android - 检查我的 Android 设备相机是否支持 HDR
- reactjs - 元素访问表达式应该有一个参数.ts(1011)
- google-cloud-platform - 为什么我在部署虚拟机或购买域时没有消耗我在谷歌云中的免费积分,这是否意味着我的卡正在收费?
- google-cloud-platform - 在欧洲 (EU) 使用 bigquery 数据时应使用哪个数据流区域