String zu int umwandeln in C
Help converting string elements to int in C++
How can I convert a string to integer in C? - Stack Overflow
String zu Int
I was attempting to read in binary numbers from a text file to manipulate in my code. I decided to take the approach to read them in as a string using the `std::getline()` function. I then stored the numbers into a vector of strings. Then I wanted to convert them into a vector of a vector of integers, so it would be easier (in my head) to sort through.
My issue is that I want to convert the string elements to integers> I tried using std::stoi(), but I continue getting the following error :no matching function for call to 'stoi(__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type&, int, int)'
num = std::stoi(bits[j].at(i));
I'm not sure what the issue is. Am I using `std::stoi` wrong? is my understanding of how to manipulate the elements in the string incorrect? Any help that you can provide would be appreciated. See below for a snippet of the code that I am trying to work on.
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<algorithm>
int main(){
std::ifstream read;
std::string line;
std::vector<std::string> bits;
std::vector<std::vector<int>> vint[5];
std::vector<int> transfer[5];
int count{0};
int count_0{0}, count_1{0};
read.open("Day_3_Input_test.txt");
std::cout << "Opening Input File!" << std::endl;
if(!read.is_open()){
std::cerr << "Failed to open Input File!!! Please check the File name/path and try again!" << std::endl;
return 1;
}
std::cout << "Input File was successfully opened! Beginning analysis." << std::endl;
while(std::getline(read, line)){
bits.push_back(line);
}
std::cout << std::endl;
int num{0};
for(int i{0}; i < 5; i++){
for(int j{0}; j < bits.size(); j++){
vint[i].emplace_back(1, std::stoi(bits[j].at(0)));
std::cout << num << " ";
}
std::cout << std::endl;
}
read.close();
return 0;
}
There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):
long long
strtonum(const char *nptr, long long minval, long long maxval,
const char **errstr);
You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:
uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
/* Could not convert. */
Anyway, stay away from atoi:
The call atoi(str) shall be equivalent to:
(int) strtol(str, (char **)NULL, 10)except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.
Robust C89 strtol-based solution
With:
- no undefined behavior (as could be had with the
atoifamily) - a stricter definition of integer than
strtol(e.g. no leading whitespace nor trailing trash chars) - classification of the error case (e.g. to give useful error messages to users)
- a "testsuite"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
typedef enum {
STR2INT_SUCCESS,
STR2INT_OVERFLOW,
STR2INT_UNDERFLOW,
STR2INT_INCONVERTIBLE
} str2int_errno;
/* Convert string s to int out.
*
* @param[out] out The converted int. Cannot be NULL.
*
* @param[in] s Input string to be converted.
*
* The format is the same as strtol,
* except that the following are inconvertible:
*
* - empty string
* - leading whitespace
* - any trailing characters that are not part of the number
*
* Cannot be NULL.
*
* @param[in] base Base to interpret string in. Same range as strtol (2 to 36).
*
* @return Indicates if the operation succeeded, or why it failed.
*/
str2int_errno str2int(int *out, char *s, int base) {
char *end;
if (s[0] == '\0' || isspace((unsigned char) s[0]))
return STR2INT_INCONVERTIBLE;
errno = 0;
long l = strtol(s, &end, base);
/* Both checks are needed because INT_MAX == LONG_MAX is possible. */
if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
return STR2INT_OVERFLOW;
if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
return STR2INT_UNDERFLOW;
if (*end != '\0')
return STR2INT_INCONVERTIBLE;
*out = l;
return STR2INT_SUCCESS;
}
int main(void) {
int i;
/* Lazy to calculate this size properly. */
char s[256];
/* Simple case. */
assert(str2int(&i, "11", 10) == STR2INT_SUCCESS);
assert(i == 11);
/* Negative number . */
assert(str2int(&i, "-11", 10) == STR2INT_SUCCESS);
assert(i == -11);
/* Different base. */
assert(str2int(&i, "11", 16) == STR2INT_SUCCESS);
assert(i == 17);
/* 0 */
assert(str2int(&i, "0", 10) == STR2INT_SUCCESS);
assert(i == 0);
/* INT_MAX. */
sprintf(s, "%d", INT_MAX);
assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
assert(i == INT_MAX);
/* INT_MIN. */
sprintf(s, "%d", INT_MIN);
assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
assert(i == INT_MIN);
/* Leading and trailing space. */
assert(str2int(&i, " 1", 10) == STR2INT_INCONVERTIBLE);
assert(str2int(&i, "1 ", 10) == STR2INT_INCONVERTIBLE);
/* Trash characters. */
assert(str2int(&i, "a10", 10) == STR2INT_INCONVERTIBLE);
assert(str2int(&i, "10a", 10) == STR2INT_INCONVERTIBLE);
/* int overflow.
*
* `if` needed to avoid undefined behaviour
* on `INT_MAX + 1` if INT_MAX == LONG_MAX.
*/
if (INT_MAX < LONG_MAX) {
sprintf(s, "%ld", (long int)INT_MAX + 1L);
assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
}
/* int underflow */
if (LONG_MIN < INT_MIN) {
sprintf(s, "%ld", (long int)INT_MIN - 1L);
assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
}
/* long overflow */
sprintf(s, "%ld0", LONG_MAX);
assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
/* long underflow */
sprintf(s, "%ld0", LONG_MIN);
assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
return EXIT_SUCCESS;
}
GitHub upstream.
Based on: https://stackoverflow.com/a/6154614/895245
You can use sprintf to do it, or maybe snprintf if you have it:
char str[ENOUGH];
sprintf(str, "%d", 42);
Where the number of characters (plus terminating char) in the str can be calculated using:
(int)((ceil(log10(num))+1)*sizeof(char))
As pointed out in a comment, itoa() is not a standard, so better use the sprintf() approach suggested in the rival answer!
You can use the itoa() function to convert your integer value to a string.
Here is an example:
int num = 321;
char snum[5];
// Convert 123 to string [buf]
itoa(num, snum, 10);
// Print our string
printf("%s\n", snum);
If you want to output your structure into a file there isn't any need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.
Quite easy that also.
string myString = "003";
int myInt = int.Parse( myString );
If you aren't sure if the string is a valid int, you can do it like this:
string myString = "003";
int myInt;
if( int.TryParse( myString, out myInt )
{
//myString is a valid int and put into myInt
}else{
//myString could not be converted to a valid int, and in this case myInt is 0 (default value for int)
}
int number = int.Parse(string)
or
int number;
int.TryParse(string, out number)
Use sprintf():
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
Making your own itoa is also easy, try this :
char* itoa(int i, char b[]){
char const digit[] = "0123456789";
char* p = b;
if(i<0){
*p++ = '-';
i *= -1;
}
int shifter = i;
do{ //Move to where representation ends
++p;
shifter = shifter/10;
}while(shifter);
*p = '\0';
do{ //Move back, inserting digits as u go
*--p = digit[i%10];
i = i/10;
}while(i);
return b;
}
or use the standard sprintf() function.