我一直有一些问题,下面这段代码...字符串转换为浮动动态
代码的主要思想是按行读入线和转换字符字符串转换为浮动并保存彩车在名为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;
}
请有人帮助我了解问题出在哪里?
看不到任何证明计算'(line + 1 +(4 * i))'的东西。它假设你的浮动长度是三个字符,但即使在你提供的数据中也不是这样。我认为这种方法是错误的,需要某种标记化,甚至可能使用strtok。 – john
是的,我认为同样的事情,但我只能用sscanf的:( – Gera
我看不到相关[标签:C++]任何声明。在你的代码中删除标签或选择其中一个 –