C:需要帮助从字符串中提取值吗
我试图从字符串中获取以分钟为单位的持续时间。我得到了这样一根弦:“1:50”。我需要将这个字符串中的分和秒提取到int变量中,然后以分钟为单位返回持续时间。所以我写了这个:C:需要帮助从字符串中提取值吗,c,string,C,String,我试图从字符串中获取以分钟为单位的持续时间。我得到了这样一根弦:“1:50”。我需要将这个字符串中的分和秒提取到int变量中,然后以分钟为单位返回持续时间。所以我写了这个: #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <conio.h> #include <string.h> int main()
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
int main()
{
char time[6]="01:30";
int duration=0, minutes=0, seconds=0;
int buffermin[3];
int buffersec[3];
int i=0;
while(i<2)
{
sscanf(time[i],"%d%d",&buffermin[i]); //Get the first two characters in the string and store them in a intger array
i++;
}
i=3;
while(i<5)
{
sscanf(time[i],"%d%d",&buffersec[i]); //Get the last two characters in the string and store them in a integer array
i++;
}
printf("%d %d %d %d", buffermin[0], buffermin[1], buffersec[0], buffersec[1]);
getch();
minutes=(buffermin[0]*10)+buffermin[1]; //Put values in array to one variable
seconds=(buffersec[0]*10)+buffersec[1]; //Same as above
seconds=seconds/60; //Turn the number of seconds to minutes
duration=seconds+minutes; //Get total duration
printf("The total duration is: %d\n",duration); //Output total duration
getch();
exit(0);
}
#包括
#包括
#包括
#包括
#包括
int main()
{
字符时间[6]=“01:30”;
整数持续时间=0,分钟=0,秒=0;
int-buffermin[3];
int-buffersec[3];
int i=0;
而(i你应该真正学会如何正确使用sscanf
。基本上,你想要实现的是:
#include <stdio.h>
int main() {
char time[] = "01:27";
int minutes;
int seconds;
// Must be double, not integer, otherwise decimal digits will be truncated
double duration;
// String has format "integer:integer"
int parsed = sscanf(time, "%d:%d", &minutes, &seconds);
// Check if input was valid
if (parsed < 2) {
// String had wrong format, less than 2 integers parsed
printf("Error: bad time format");
return 1;
}
// Convert to minutes (mind the floating point division)
duration = (seconds / 60.0) + minutes;
printf("Duration: %.2f minutes\n", duration);
return 0;
}
#包括
int main(){
字符时间[]=“01:27”;
整数分钟;
整数秒;
//必须是双精度,而不是整数,否则十进制数字将被截断
双倍持续时间;
//字符串的格式为“整数:整数”
int parsed=sscanf(时间、%d:%d、&分、&秒);
//检查输入是否有效
if(解析<2){
//字符串格式错误,分析的整数少于2个
printf(“错误:错误时间格式”);
返回1;
}
//转换为分钟(注意浮点除法)
持续时间=(秒/60.0)+分钟;
printf(“持续时间:%.2f分钟\n”,持续时间);
返回0;
}
这是你写的,发生了什么?请编辑问题。它做了什么?它产生了什么输出?它的行为以什么方式违背了你的期望?你的问题是什么?这个问题似乎是离题的,因为它不是一个问题。而你的问题是?……你的代码表明你对sscanf的工作原理以及浮点和整数运算之间的区别。C非常容易学习(在基本的中级水平上),但你必须学习它。你真的应该在编写代码之前学习一本好的C语言书。这会帮你省去很多麻烦。谢谢你,如果可以的话,我会给你投票。解析值做什么?它计算解析了多少个数。它们必须是2,分和秒。如果发现少于2个数,则字符串的形式不正确关于你上面的评论,请点击。有关于c语言书籍的推荐吗?不幸的是,我没有推荐,因为我是在K&R上第一次学习c语言的(克尼汉和里奇),这是一本70年代的书,其中提到了C的过时版本,我及时了解了C89和C99的最新添加内容。我建议您不要阅读Herbert Schildt的任何书和任何特定于Windows的书(它们的特定API非常非标准),但除此之外,你可以开始获取一些标题,然后搜索对这些标题的意见。初学者列表中的第一个似乎是最适合你的。