字符串转换为浮动动态
我一直有一些问题,下面这段代码...字符串转换为浮动动态
代码的主要思想是按行读入线和转换字符字符串转换为浮动并保存彩车在名为nfloat
的数组中。
的输入是包含此一.txt
:Ñ =串的数量,在这种情况下Ñ = 3
3 [9.3,1.2,87.9]
[1.0,1.0]
[0.0,0.0,1.0]
的第一个数字,3
是载体的,因为我们可以看到数在图像中,但该数字不是静态的,输入可以是5
或7
等,而不是3
。
到目前为止,我已经开始做了以下(仅1载体的情况下),但代码中有一些内存错误,我认为:
int main(){ int n; //number of string, comes in the input
scanf("%d\n", &n);
char *line = NULL;
size_t len = 0;
ssize_t read;
read = getline(&line,&len,stdin); //here the program assigns memory for the 1st string
int numsvector = NumsVector(line, read);//calculate the amount of numbers in the strng
float nfloat[numsvector];
int i;
for (i = 0; i < numsvector; ++i)
{
if(numsvector == 1){
sscanf(line, "[%f]", &nfloat[i]);
}
else if(numsvector == 2){
if(i == 0) {
sscanf(line, "[%f,", &nfloat[i]);
printf("%f ", nfloat[i]);
}
else if(i == (numsvector-1)){
sscanf((line+1), "%f]", &nfloat[i]);
printf("%f\n", nfloat[i]);
}
}
else { //Here is where I think the problems are
if(i == 0) {
sscanf(line, "[%f,", &nfloat[i]);
printf("%f\n", nfloat[i]);
}
else if(i == (numsvector-1)) {
sscanf((line+1+(4*i)), "%f]", &nfloat[i]);
printf("%f\n", nfloat[i]);
}
else {
sscanf((line+1+(4*i)), "%f,", &nfloat[i]);
printf("%f\n", nfloat[i]);
}
}
}
好了,问题来与sscanf
说明,我认为在两个浮筒或一个字符串的情况下,代码工作正常,但在3个或多个浮标的情况下,代码不能很好地工作,我不明白为什么...
这里我附加功能,但它似乎是正确的...问题的重点仍然是主要的。
int NumsVector(char *linea, ssize_t size){ int numsvector = 1; //minimum value = 1
int n;
for(n = 2; n<= size; n++){
if (linea[n] != '[' && linea[n] != ']'){
if(linea[n] == 44){
numsvector = numsvector + 1;
}
}
}
return numsvector;
}
请有人帮助我了解问题出在哪里?
回答:
好 - 如果您更换当前与这个循环中,你nfloat数组应该在它的正确的数字结束。
/* Replaces the end ] with a , */ line[strlen(line) - 1] = ',';
/* creates a new pointer, pointing after the first [ in the original string */
char *p = line + 1;
do
{
/* grabs up to the next comma as a float */
sscanf(p, "%f,", &nfloat[i]);
/* prints the float it's just grabbed to 2 dp */
printf("%.2f\n",nfloat[i]);
/* moves pointer forward to next comma */
while (*(p++) != ',');
}
while (++i < numsvector); /* stops when you've got the expected number */
以上是 字符串转换为浮动动态 的全部内容, 来源链接: utcz.com/qa/265273.html