c - 用c中的空格扫描多维字符串
问题描述
我正在尝试制作一个简单的代金券。所以,我使用了多维字符串。但是面临包括这些字符串中的空间在内的麻烦。相反,我将单词作为输入。但是有没有办法包含空间?我的代码如下 -
#include<stdio.h>
#include<string.h>
int main(){
int sum =0, n, i;
puts("Please input how many transactions you want to enlist: ");
scanf("%d", &n);
char list[301][51];
int amount[301];
puts("Please enter the name of your transaction and the amount: (Press space or enter to toggle between name and amount . And avoid using spaces in the name; use underscore instead.)");
for(i=0; i<n; i++){
scanf("%s %d", &list[i], &amount[i]);
sum += amount[i];
}
list[0][n+1] = '\0';
amount[n+1] = '\0';
puts("");
printf("\t\t\t\t Voucher\n\n");
puts(" Ser.|\t Name \t\t\t\t\t\t\t|Amount");
puts("------------------------------------------------------------------------------------------------------------");
for(i=0; i<n; i++ ){
printf(" %03d |\t %-50s\t|%6d\n", i+1, list[i], amount[i]);
}
puts("------------------------------------------------------------------------------------------------------------");
printf(" | Total\t\t\t\t\t\t\t|%6d", sum);
puts("");
return 0;
}
解决方案
为此,您可以使用说明%[
scanf
符来读取所有字符,直到您碰到一个数字,然后将其写入list[i]
.
这会给你留下一个尾随空格list[i]
,但如果你不想要它可以修剪。
然后scanf
调用可能看起来像
scanf(" %50[^0-9]%d", list[i], &amount[i]);
请注意格式字符串中的前导空格,以告知scanf
跳过空格(如上一行中的换行符),以及宽度说明符不超过可以容纳的内容line[i]
。
当然,这会阻止您在读取的字符串中包含数字。要解决这个问题,你需要走一条更复杂的路线。
例如通过将整行读入缓冲区,然后找到字符串中的最后一个空格。然后,您可以将最后一个空格之前的内容复制到list[i]
,并将之后的内容转换为 的int
值amount[i]
。
推荐阅读
- java - 我正在尝试启动附近的 android master 但给我这个错误
- arcgis - 功能的 Arcgis 服务器 CreateReplica REST API 不起作用
- reactjs - 无法在反应中设置未安装组件的状态
- ios - 如何在 swift 4 中使用“WWCalendarTimeSelector”第三方
- java - 在使用 .peek() 的 java 流中被认为仅用于调试目的,日志记录是否被视为调试?
- python - 在 pandas 中转换自定义日期格式
- xslt - how do I nest elements dynamically using XSLT?
- regex - 在 Perl 中,如何匹配两个连续的回车符?
- python - 为什么我的代码无法从谷歌加载 MNIST 数据集?
- python-3.x - Python requests.get(url) 返回 javascript 代码而不是页面 html