简体   繁体   中英

How to get the length of a string in c, if it has integers in it

I am familiar with the sizeof operation in C, but when I use it for the string "1234abcd" it only returns 4 , which I am assuming is accounting for the last 4 characters. So how would I get this to be a string of size 8?

specific code is as follows:

FILE *in_file;
in_file = fopen(filename, "r");     
if (in_file == NULL) {
    printf("File does not exist\n");
    return 1;
}

int val_to_inspect = 0;

fscanf(in_file, "%x", &val_to_inspect);

while (val_to_inspect != 0) {
    printf("%x", val_to_inspect);
    int length = sizeof val_to_inspect;
    printf("%d", length);

Again, the string that is being read from the file is "1234abcd" , just to clarify.

There're a couple of issues here:

sizeof operator returns the size of the object. In this case it returns the size of val_to_inspect , which is an int . http://en.cppreference.com/w/cpp/language/sizeof

fscanf reads from a stream and interprets it. You are only scanning an integer ("%x"), not a string. http://en.cppreference.com/w/cpp/io/c/fscanf

Lastly, if you actually had a nil-terminated string, to get its length you could use strlen() .

TL;DR , to get the length of a string, you need to use strlen() .

That said, be a little cautious while using sizeof , it operates on the data type. So, if you pass a pointer to it, it will return you the size of the pointer variable, not the length of the string it points to.

In several important ways, only some of which have anything to do with sizeof , you are mistaken about what your code actually does.

FILE *in_file;
in_file = fopen(filename, "r");     
if (in_file == NULL)
  {
    printf("File does not exist\n");
    return 1;
  }

Kudos for actually checking whether fopen succeeded; lots of people forget to do that when they are starting out in C. However, there are many reasons why fopen might fail; the file not existing is just one of them. Whenever an I/O operation fails, make sure to print strerror(errno) so you know the actual reason. Also, error messages should be sent to stderr , not stdout , and should include the name of the affected file(s) if any. Corrected code looks like

if (in_file == NULL)
  {
    fprintf(stderr, "Error opening %s: %s\n", filename, strerror(errno));
    return 1;
  }

(You will need to add includes of string.h and errno.h to the top of the file if they aren't already there.)

int val_to_inspect = 0;
fscanf(in_file,"%x", &val_to_inspect);

This code does not read a string from the file. It skips any leading whitespace and then reads a sequence of hexadecimal digits from the file, stopping as soon as it encounters a non-digit, and immediately converts them to a machine number which is stored in val_to_expect . With the file containing 1234abcd , it will indeed read eight characters from the file, but with other file contents it might read more or fewer.

(Technically, with the %x conversion specifier you should be using an unsigned int, but most implementations will let you get away with using a signed int.)

(When you get more practice in C you will learn that scanf is broken-as-specified and also very difficult to use robustly, but for right now don't worry about that.)

while (val_to_inspect != 0) {
    printf("%x", val_to_inspect);
    int length = sizeof val_to_inspect;
    printf("%d", length);
}

You are not applying sizeof to a string, you are applying it to an int . The size of an int , on your computer, is 4 char s, and that is true no matter what the value is .

Moreover, sizeof applied to an actual C string (that is, a char * variable pointing to a NUL-terminated sequence of characters) does not compute the length of the string. It will instead tell you the size of the pointer to the string, which will be a constant (usually either 4 or 8, depending on the computer) independent of the length of the string. To compute the length of a string, use the library function strlen (declared in string.h ).

You will sometimes see clever code apply sizeof to a string literal , which does return a number related to (but not equal to!) its length. Exercise for you: figure out what that number is, and why sizeof does this for string literals but not for strings in general. (Hint: sizeof s will return a number related to s 's string length when s was declared as char s[] = "string"; , but not when it was declared as char *s = "string"; .)

As a final note, it doesn't matter in the grand scheme of things whether you like your opening braces on their own lines or not, but pick one style and stick to it throughout the entire file . Don't put some if opening braces on their own lines and others at the end of the if line.

It's better to create own counter to find the length of "1234abcd" by reading the character by character.

FILE *in_file;
char ch;
int length=0;

in_file = fopen("filename.txt", "r");
if (in_file == NULL)
{
    printf("File does not exist\n");
    return 1;
}
while (1) {
    ch = fgetc(in_file);
    printf("%c", ch);
    if (ch == EOF)
        break;
    length++;
}
fclose(in_file);
printf ("\n%d",length);

Everyone, thank you for all the feedback. I realize I made a lot of mistakes with the original post, but im just switching to c from c++, so a lot of the things I'm used to cant really be applied the same way. This is all tremendously helpful, it's good to have a place to go to.

Len = sizeof(你的字符串)/ sizeof(char)-1 -1是eof字符null如果你想从特定的开始索引得到任何长度,那就做Len-index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM