c - 如何在c中添加多个带空格的字符串?
问题描述
我正在尝试在数组中存储多个带有空格的字符串。
#include<stdio.h>
#define L 30
void main(){
puts("\t+----------------------+\n\t| Contacts Application |\n\t+----------------------+\n");
int noc; // number of contacts
printf(" How many contacts do you want to store: ");
scanf("%d", &noc);
char name[noc][L];
int number[noc];
int a, b; // for counters in loop in switch
if(noc>0){
for(int i = 0; i < noc; i++){
printf("\n\tName %d: ", i+1);
//scanf("%s", &name[i]);
fgets(name[i], L, stdin);
printf("\tNumber: ");
scanf("%d", &number[i]);
}
/** This will clear the screen **/
#ifdef _WIN64
system("cls");
#elif __linux__
system("clear");
#endif
puts("\n\tAll contacts have been saved successfully.\n");
puts("\t1. Show all the contacts.");
puts("\t2. Search any contact.\n");
int choice;
printf("\tEnter your choice: ");
scanf("%d", &choice);
switch(choice){
case 1:
for(int a = 0; a < noc; a++){
printf("\n\t %d: %s - %d", a+1, name[a], number[a]);
}
break;
case 2:
//searchContact();
default:
puts("\n\tInvalid option, please try again.\n");
}
} else{
puts("\nPlease enter more than zero.");
}
} // main function
而且这段代码不起作用,不知道为什么,@kutt 在评论中添加了一个示例,它可以工作,但这不起作用,为什么?
当执行直接传递到 &number 的 scanf() 时,可以做些什么来解决这个问题。
解决方案
如果在andfgets
前面添加空格,则不必使用。您还应该测试 scanf 的返回值以检查操作是否成功。%d
%[^\n]
这是固定代码。
如果此代码在输入值不是数字的情况下重复请求数字。
#include<stdio.h>
#include <stdlib.h>
void main(){
puts("\t+----------------------+\n\t| Contacts Application |\n\t+----------------------+\n");
int noc; // number of contacts
int cnt;
do {
printf(" How many contacts do you want to store: ");
cnt = scanf("%d", &noc);
} while (cnt != 1);
if(noc>0){
char name[noc][30];
int number[noc];
int a, b; // for counters in loop in switch
for(int i = 0; i < noc; i++){
printf("\n\tName %d: ", i+1);
scanf(" %[^\n]", &name[i]);
do {
printf("\tNumber: ");
cnt = scanf(" %d", &number[i]);
} while (cnt != 1);
}
/** This will clear the screen **/
#ifdef _WIN64
system("cls");
#elif __linux__
system("clear");
#endif
puts("\n\tAll contacts have been saved successfully.\n");
puts("\t1. Show all the contacts.");
puts("\t2. Search any contact.\n");
int choice;
printf("\tEnter your choice: ");
scanf("%d", &choice);
switch(choice){
case 1:
for(int a = 0; a < noc; a++){
printf("\n\t %d: %s - %d", a+1, name[a], number[a]);
}
break;
case 2:
//searchContact();
default:
puts("\n\tInvalid option, please try again.\n");
}
} else{
puts("\nPlease enter more than zero.");
}
} // main function
推荐阅读
- php - Laravel 关系 - 从多个模型中提取 ID
- javascript - 防止其他人连接到 NodeJS 上的 WebSocket?(WS 模块)
- azure - Azure CosmosDB 调试存储过程:使日志可读
- python - 在 Django 中访问 Null DecimalField 时出现 RecursionError
- primefaces - 为什么 'p:ajax update' 无法更新 ap:tree?
- javascript - 在角度项目上安装引导程序
- linux - 与硬编码字符串相比,打印命令输出时 bash 中的不同行为
- c# - 使用 ViewBag 列表从 DropDownListFor 获取所选值
- php - 在简短描述产品 WooCommerce 中显示带有价格的自定义文本
- javascript - 如何拦截非 JSON 的响应