How Do I Read in an Integer From Text File and Store It a Variable in C++

laptop coding language

Dennis Ritchie created the C programming linguistic communication in 1972. The language has its roots in the B language, released in 1970. Among other software, Linux and MySQL are written in C. Because it's so unproblematic all the same so powerful, C has influenced many programming languages.

C++, for example, is a programming language derived directly from C. C is a general-purpose, structured, and procedural programming language. There are several C compilers available for converting C lawmaking to the auto language across multiple hardware platforms. System programming uses C since its programs are fast and can handle low-level tasks. The language itself has been written in associates linguistic communication.

We will examine means to convert strings to integers (numeric values) using the C programming linguistic communication in this beginner's tutorial. You should be familiar with the basics of programming.

Overview of strings in C

In the C language, a string is the type used to store any text, including alphanumeric and special characters. Internally, it'southward represented as an assortment of characters. Ane terminates a string in C with a Nix character, which is why they are called "nix-terminated strings." To represent a string in C, enclose it in double quotes.

Internally, a string is represented in C like this, where \0 is the nothing character:

| T | h | i | s |  | a |  | s | t | r | i | due north | g | \0 |

Many C programs use strings and associated properties. The necessary header file for string functions is string.h. The operations possible on strings include calculating the string length, concatenating multiple strings, comparing multiple strings, and copying strings. Here is an example of creating a string in C and some of its methods:

          #include <stdio.h> #include <string.h>  int main () {     char string1[12] = "Hello";    char string2[12] = "World";    char string3[12];    int  len ;     /* copies string1 into string3 */    strcpy(string3, string1);    printf("strcpy( string3, string1) :  %south\north", string3 );     /* concatenates string1 and string2 */    strcat( string1, string2);    printf("strcat( string1, string2):   %s\n", string1 );     /* total lenghth of string1 after concatenation */    len = strlen(string1);    printf("strlen(string1) :  %d\n", len );     render 0; }        

What is type conversion?

Many times in C programs, expressions comprise variables and constants of different information types. For adding purposes, they must convert to the same data type. Converting ane data type to another is chosen type conversion.

In C, nosotros take two types of type conversion:

  1. Implicit Type Conversion. The compiler does this automatically. Programmers don't play any role hither.
  2. Explicit Type Conversion. Here the developer is responsible for the type conversion. This is also called typecasting. The syntax is as follows:
          (datatype) expression;        

The in a higher place item is a bandage operator. Accept a look at this example:

          char a; int b; a = (char)b;        

This is a simple manner to catechumen an integer to a grapheme type. Hither, "a" is of graphic symbol data type and b is of integer data type. It's not possible to assign the value of variable b to variable a every bit they are of different data types. So, we typecast integer b to grapheme in this example. At present, both a and b are of character information type.

How to Convert String to Integer in the C Linguistic communication

Sometimes, a number is input as a cord. To use it for any mathematical operation, we must catechumen the string to an integer. In that location are few ways of converting string to integer values using C:

  1. The beginning method is to manually convert the string into an integer with custom lawmaking.
  2. The 2nd method is to use the atoi function included with the C standard library.
  3. The tertiary method is using the sscanf office included in the C standard library.
  4. The fourth method uses the strtol() function included in the C standard library.
  5. The fifth method uses the strtoumax() function included in the C standard library.

Example 1: Programme to manually convert a string to an integer

Beneath is a list of ASCII (American Standard Lawmaking for Information Interchange) characters and their decimal value.

ASCII Character Decimal Value
0 48
ane 49
2 50
3 51
4 52
v 53
6 54
seven 55
8 56
9 57

Numbers are stored in a string past their ASCII character value. So we have to exercise math in order to retrieve a value we can use equally an integer. In order to get the decimal value of each string element, we must subtract it with the decimal value of grapheme "0." Here is an example to make this clearer:

          #include <stdio.h> #include <cord.h>  master() {   char num[l];   int  i, len;   int result = 0;      printf("Enter a number: ");   gets(num);   len = strlen(num);  	for(i=0; i<len; i++){ 		issue = issue * 10 + ( num[i] - '0' ); 	}  	printf("%d", upshot); }        

Initially, in this programme, nosotros include stdio.h and string.h from the C standard library. This lets us employ the functions that are office of these header files. The C programming language doesn't automatically include functions like these. You must import them into your software to employ them.

The chief office executes the C programme. Hence, it's mandatory to accept 1 in every C programme. The program lawmaking is written within the curly braces of the main function.

Inside the main function we first define and declare the dissimilar variables forth with their information types. Variables i, len, and result are declared as of integer information type. The event variable initializes to null.

The printf() office is and so called to display the message "enter a number" on the output screen. gets(num) will read the input number and store information technology as a string. In this case, the string is an assortment of characters pointed to by num. Then, nosotros calculate the length of the cord using the strlen() function.

Next, we loop through the string and convert the string into decimal values. Finally, the string is converted into an integer and printed on the screen.

Example ii: A program to convert a string to an integer using the atoi() function

The atoi() office converts a string information blazon to integer data type in the C language. The syntax of this role is:

          int atoi((const char * str);        

Here, str is of type pointer to a character. The const keyword makes variables not-modifiable. This function returns an integer value after execution. We include stdlib.h considering that's where the atoi() function is. This header file contains all the type casting functions used in the C language.

          #include <stdio.h> #include <stdlib.h>  main() {   char x[10] = "450";   int consequence = atoi(x);   printf("integer value of the string is %d\n", outcome); }        

Note that the string value used with this part must be a sequence of characters interpretable equally a numeric value. The function will stop reading the input one time it encounters a not-numeric grapheme. So if nosotros changed the code higher up to expect similar this:

          #include <stdio.h> #include <stdlib.h>  master() {   char x[ten] = "99x677";   int result = atoi(x);   printf("integer value of the string is %d\n", result); }        

The plan above would impress out: "integer value of the cord is 99".

The atoi part too ignores any leading whitespace characters, merely if encountered within the cord, information technology volition stop processing the cord. It will as well return 0 if it can't convert the string into an integer. If at that place is an overflow, it will return undefined. The atoi function too doesn't recognize decimals or exponents. So y'all volition have to write your code to business relationship for the fact that atoi just silently fails instead of throwing an error when it can't catechumen a string to an integer. And the fact that the function returns a 0 when the conversion didn't piece of work can exist hard to bargain with, since information technology's a valid integer.

Example 3: A programme to convert a string to an integer using the sscanf() function

The sscanf() role acts a little differently. It reads formatted text from an input cord. This is like to the sscanf() function, merely sscanf() can read data input from a string instead of the console. Here is the annunciation for the sscanf() office:

          int sscanf(const char *str, const char *format, storage_variables)        

The first parameter is the string yous desire to parse. The second parameter is the format you want to apply to the cord. You can add equally many parameters that the role can take in gild to store the value beingness read from the pointer. Here, if a regular variable stores the value instead of a pointer, and so the variable name must follow the & sign.

The format parameter takes a specific type of value called a format specifier that formats the data in the string parameter in a specific way. Each format specifier grapheme must precede the % character. Here are the format specifiers you lot can use:

Symbol Blazon
south string
c single grapheme
d decimal integer
eastward, E, f, one thousand, G floating points
u unsigned integer
x, X hexadecimal number

The bare minimum for a format specifier is the % symbol and 1 of the characters above. We can use either the symbol for the decimal integer or the unsigned integer, depending on what we desire to reach. It's good to note that we tin really use this function to convert a decimal, which the atoi() part can't practice. For that, we can use "%d."

But a format specifier tin can concur more information than that. Here is its prototype:

          [=%[*][width][modifiers]type=]        

Here we see the start character is the % symbol. The side by side is an optional asterisk, which indicates the information that will be read from the string but ignored. The next is the width value, which specifies the maximum amount of characters you want to read from the string.

Hither is an instance in code using width:

          #include <stdio.h>  int chief() { 	unsigned char text[]="1234"; 	int integerValue; 	 	sscanf(text, "%04d", &integerValue); 	printf("Integer value is: %d", integerValue); 	 	return 0; }        

In the function above, we create a string containing "1234" and instantiate an integerValue variable to concur the integer nosotros are going to parse out of the string. Side by side is the sscanf() function. The first parameter is our string and the terminal is a pointer to the integer we only instantiated. The format parameter tells the office we want to parse a decimal number from the cord and that we simply desire 4 characters. The result of running it is:

Integer value is: 1234

But we can remove the width value in the format similar below and get the same outcome:

          #include <stdio.h>  int main() { 	unsigned char text[]="1234"; 	int integerValue; 	 	sscanf(text, "%d", &integerValue); 	printf("Integer value is: %d", integerValue); 	 	render 0; }        

Example 4: A programme to catechumen a string to an integer using the strtol() function

The C strlol() role converts a string to a long integer. This is a 64-bit integer. The standard integer is 32-bit. This is a expert role to use if yous expect to exist converting strings that comprise long numbers. It functions similarly to the atoi() function. It ignores any whitespace at the showtime of a string, but it volition stop processing the string when it encounters a whitespace or whatever other non-digit in the string.

Here is the syntax of the strlol() function:

          long int strtol(const char *str, char **endptr, int base);        

The showtime parameter is a pointer to the string that you want to convert. The second parameter is a pointer used by the function that points to the first non-integer graphic symbol the function runs into when it stops processing. The final parameter is the base of the number being converted. It can exist a number between 2 and 32 or a special value of 0.

Here is a programme that will catechumen a string into a long integer:

          #include <stdio.h> #include <stdlib.h> #include <cord.h>  int main() {     char str[10];     char *ptr;     long value;          strcpy(str, " 12345");     value = strtol(str, &ptr, 10);     printf("the long integer value is %ld\n", value);      render 0; }        

In the beginning of the main function in a higher place, we instantiate the three variables we are going to demand to demonstrate the strlol() function: a cord, a pointer, and a long integer. So we set the value of our string to " 12345″ with a leading space to demonstrate that the part will strip leading white space. Then we pass the string and the pointer to strlol() along with 10 as the last parameter because we are parsing decimal numbers that have a base of 10. The result of the role is:

the long integer value is 12345

Example 5: A program to convert a string to an integer using the strtoumax() part

The C strtoumax() is very similar to the strlol() function, but they return intmax_t value, which is the largest possible integer type in C. Its syntax is even the aforementioned:

          long int strtoumax(const char *str, char **endptr, int base of operations);        

And here is an example using the strtoumax function:

          #include <stdio.h> #include <stdlib.h>  int main() {   char int[ten] = " 98765", *end;      unsigned long x = strtoumax(int, &end, 10);   printf("the integer value is %ld\n", x);      render 0; }        

This office is like to the one we wrote for the strlol() function. Here is the result of this plan:

the integer value is 98765

Even more means to convert a string to an integer in C

These aren't the only functions you tin apply in C to convert strings to integers. It actually is a flexible linguistic communication and gives you a lot to choose from. Hither are those other functions:

  • strtoul: Aforementioned every bit strtol, merely it works with unsigned integers instead of signed integers.
  • wcstoul: Aforementioned as the strtoul role, but it handles broad graphic symbol strings.
  • strtoll: Like to strtol except it returns a long long int value and accepts numbers with a larger range.
  • wcstoll: Similar to stroll, but information technology handles broad character strings.
  • strtoimax: Similar to strtoumax, but it works with signed instead of unsigned integers.

Conclusion

Even if there is numerical value in a string, you tin can't perform whatever calculations on information technology in the C programming language unless y'all catechumen it to an integer showtime. Fortunately, there are a lot of ways to do this with the C standard library. You tin can write your own function or employ one of the many built-in conversion functions that come up with C. Each part converts integers slightly differently, so which yous use depends on the size of the integer you volition be parsing and what you will do with it.

careyfromin.blogspot.com

Source: https://blog.udemy.com/c-string-to-int/

0 Response to "How Do I Read in an Integer From Text File and Store It a Variable in C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel