Read space separated numbers from char array to separate int(s) - c++

I have a char array (lets' say "13 314 43 12") and i want to put the first number (13) into a separate integer . how do i do that ? is there any way like splitting the first number into 10 + 3 and then adding them to the int ?

I am not sure what you mean by getting 1 and 3, but if you want to split the space-separated string into integers I suggest using a stream.
std::istringstream iss(s);
int n;
while(iss >> n)
{
std::cout << "Integer: " << n << std::endl;
}
[edit] Alternatively, you could parse the string yourself, something like this:
char* input = "13 314 43 12";
char* c = input;
int n = 0;
for( char* c = input; *c != 0; ++c )
{
if( *c == ' ')
{
std::cout << "Integer: " << n << std::endl;
n = 0;
continue;
}
n *= 10;
n += c[0] - '0';
}
std::cout << "Integer: " << n << std::endl;

#include <cstring>
#include <iostream>
#include <stdlib.h>
int main ()
{
char str[] = "13 45 46 96";
char * pch = strtok (str," ");
while (pch != NULL)
{
std::cout << atoi(pch) << "\n"; // or int smth=atoi(pch)
pch = strtok (NULL, " ");
}
return 0;
}

If you just want the first number, just use a function like atoi() or strtol(). They extract a number until it runs into the null terminated character or a non-numeric number.

According to your question I think following code will give some idea.
#include <string>
#include <iostream>
using namespace std;
int main(){
char s[] = "13 314 43 12";
//print first interger
int v = atoi(s);
cout << v << std::endl;
//print all integer
for (char c : s){
if (c == ' ' || c == '\0'){
}else{
int i = c - '0';
cout << i << std::endl; // here 13 print as 1 and 3
}
}
}
If you want to print first number you can use
int v = atoi(s);
cout << v << std::endl;
If you want to split and print all integers Ex: 13 as 1,3
for (char c : s){
if (c == ' ' || c == '\0'){
}else{
int i = c - '0';
cout << i << std::endl; // here 13 print as 1 and 3
}
}

Related

How to convert multiple numbers in a string into ints

I am confused as to how to take multiple strings that have numbers in them and convert them into an int. I have multiple lines of strings that are stored in data into ints and then insert them into a 2 dimensional arrays called values. A similar question was posted earlier on StackOverflow; however it does not seem to be working for me. I printed out what each line in data is, each string in data is as follows.
75
95 64
17 42 82
18 35 87 10
However when I output the numbers from value by using two for loops in main, it outputs as this.
75
0
0
0
95
64
0
0
95
64
0
0
17
42
82
0
17
42
82
0
18
35
87
10
18
35
87
10
0
0
0
0
I found that there are 8 columns and 8 elements in the array values when I printed the sizeof(values) and sizeof(values[0]); however, it appears that the program terminated as the last print statement, where I print hello does not occur. I provided the code I'm using below. I would like to know why this is occurring
and how I can fix it? Thanks.
//const char DELIMITER = ' ';
int **values, // This is your 2D array of values, read from the file.
**sums; // This is your 2D array of partial sums, used in DP.
int num_rows; // num_rows tells you how many rows the 2D array has.
// The first row has 1 column, the second row has 2 columns, and
// so on...
bool load_values_from_file(const string &filename) {
ifstream input_file(filename.c_str());
if (!input_file) {
cerr << "Error: Cannot open file '" << filename << "'." << endl;
return false;
}
input_file.exceptions(ifstream::badbit);
string line;
vector<string> data;
try {
while (getline(input_file, line)) {
data.push_back(line);
num_rows ++;
}
input_file.close();
} catch (const ifstream::failure &f) {
cerr << "Error: An I/O error occurred reading '" << filename << "'.";
return false;
}
for(int x = 0; x < data.size(); x++){
cout << data[x] << endl;
}
//https://stackoverflow.com/questions/1321137/convert-string-containing-several-numbers-into-integers
//Help on making multiple numbers in a string into seperate ints
values = new int*[num_rows];
vector<int> v;
for(int y = 0; y < data.size(); y++){
istringstream stream(data[y]);
values[y] = new int[y + 1];
int z = 0;
while(1) {
int n;
stream >> n;
if(!stream)
break;
values[y][z] = n;
z++;
}
z = 0;
}
sums = values;
return true;
}
int main(int argc, char * const argv[]) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <filename>" << endl;
return 1;
}
string filename(argv[1]);
if (!load_values_from_file(filename)) {
return 1;
}
cout << sizeof(values) << endl;
cout << sizeof(values[0]) << endl;
for(int x = 0; x < sizeof(values); x++){
for(int y = 0; y < sizeof(values[x]); y++){
cout << values[x][y] << endl;
}
cout << endl;
}
cout << "hello" << endl;
return 0;
}
See this :
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string str;
ifstream fs("D:\\Myfolder\\try.txt", ios::in);
stringstream ss;
std::string item;
if (fs.is_open())
{
ss << fs.rdbuf();
str = ss.str();
cout << str << endl;
fs.close();
}
cout << "\n\n Output \n\n";
while (std::getline(ss, item, ' '))
{
cout << std::atoi(item.c_str()) <<" ";
}
return 0;
}

how can I print ascii code value in c++ in this way?

I'd like to show each letter's ascii code
for example
Input: HelloWorld
Ascii Value: 72 + 101 + 108 ... = 1100
And here's my now-code
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char str[32] = { 0 };
int value = 0, i;
cout << "Input: ";
cin >> str;
for (i=0;i<32;i++)
{
value += str[i];
}
cout << "Ascii Value:" << value << endl;
return 0;
}
I only can take the total value of ascii code such as 1100,
not every code value of each letters such as 7 + 11 + ... = 1100.
How can I fix it?
You should use a string for your input (it's c++, not c). Your for loop sums 32 characters, even if the user inputs a shorter string (the programm will read random values from memory). For conversion from int to char you can use stringstream. This results in
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string input;
std::stringstream sstr;
int value = 0;
std::cout << "Input: ";
std::cin >> input;
for (int i = 0; i < input.size(); i++) {
sstr << int(input[i]) << " + ";
value += input[i];
}
std::string str(sstr.str());
std::cout << "Ascii Value:" << str.substr(0, str.size() - 3) << " = " << value << std::endl;
return 0;
}

Breaking an array of chars into words

i need a little help with this problem,
How do you break a char array like this "char* text" into individual words based on specific delimiters and save them in the form "char* text[]" without using the strtok function or any libraries besides "iostream".
In a normal situation i would use strings instead of char arrays and the strtok function, but in this situation, i am simply not allowed to.
Thanks,
Update:
i have included what i have attempted
#include <iostream>
#include <fstream>
//#define MAX_CHARS_PER_LINE = 512;
//#define MAX_TOKENS_PER_LINE = 5;
using namespace std;
char stringToken(char* input_string);
int main(int argc, char* argv[])
{
char input_string[512];
ifstream infile;
infile.open(argv[1]);
while(!infile.eof())
{
infile.getline(input_string, 512);
cout << "Main line: " << input_string << endl;
stringToken(input_string);
}
infile.close();
return 0;
}
char stringToken(char* input_string)
{
//char* word;
//cout << "String token function: " << input_string << endl;
/*while(input_string >> word)
{
cout << word << endl;
}*/
char *tempone;
char *temptwo[5];
int ii=0,
jj=0;
while(input_string[ii] != '\0' && jj<5)
{
if((int)input_string[ii]!= 32 && (int)input_string[ii]!= 9 && (int)input_string[ii] != 44)
{
tempone[ii]=input_string[ii];
//cout << "\n\nindiv char" << input_string[ii] << "\t\t" << (int)input_string[ii] << "\n\n";
}
else
{
temptwo[jj]=tempone;
jj++;
//testing
cout << temptwo << endl;
}
ii++;
}
return 0;
}
Here a pseudo code
words split(line, delims)
{
nb_words = cound_words(line);
words = allocate_words(nb_words + 1); // words is a array of pointer
i = 0
j = 0
while true
{
while line[i] in delims // we transform every delims into a end string
{
line[i] = end_string
i++
}
if line[i] not end_string
{
words[j] = line + i // we stock the address of line[i]
j++
while line[i] not in delims and line[i] not end_string
{
i++
}
}
else
{
words[j] = NULL // we end the array by NULL pointer
return words
}
}
}
count_word use a similar loop. I let you find it. The purpose of this algorithm is to transform the line into multiple word. So line must life as long that you use words.

ASCII Dec to Char in C++

I want to get every characters of ASCII in normal char. If I only put char key only, it would return dec.
My request:
char alph = //ascii dec to normal char
For example: A in dec is 65
Note: I don't have the characters, but I do have the ASCII codes in dec like 65.
because I need user input like 65
In this case you can do this:
#include <iostream>
using namespace std;
int main() {
int code;
cout << "Enter a char code:" << endl;
cin >> code;
char char_from_code = code;
cout << char_from_code << endl;
return 0;
}
This will ouput:
Enter a char code:
65
A
It seems you have misunderstood the concept.
The numerical value is always there. Whether you print it as the letter or the numerical value depends on how you print.
std::cout will print chars as letters (aka chars) so you'll need to cast it to another integer type to print the value.
char c = 'a';
cout << c << endl; // Prints a
cout << (uint32_t)c << endl; // Prints 97
cout << endl;
uint32_t i=98;
cout << i << endl;
cout << (char)i << endl;
Output:
a
97
98
b
This is the method, very simple and then just need to make your own user interface to get input dec
#include <iostream>
using namespace std;
int main() {
int dec = 65;
cout << char(dec);
cin.get();
return 0;
}
Looks like you need hex/unhex converter. See at boost, or use this bicycle:
vector<unsigned char> dec2bin( const string& _hex )
{
vector<unsigned char> ret;
if( _hex.size() < 2 )
{
return ret;
}
for( size_t i = 0; i <= _hex.size() - 2; i += 2 )
{
string two = string( _hex.data() + i, 2 );
stringstream ss( two );
string ttt = ss.str();
int tmp;
ss >> /*hex >>*/ tmp;
unsigned char c = (unsigned char)tmp;
ret.insert( ret.end(), c );
}
return ret;
}
int main()
{
string a = "65";
unsigned char c = dec2bin( a )[0];
cout << (char)c << endl;
return 0;
}

C++ Bitset array, accessing values

I've got the task to create a graph's adjacency matrix from a list of adjacent nodes, stored in a file (don't need the weights) into a bitset array in C++. I successfully read the adjacent nodes from the file, but when I try to store it in the bitset array the outcome is not right.
My function is the following:
bitset<N>* read_graph(string filepath)
{
FILE *fp;
char line[100];
bitset<N> bs[N];
fp = fopen(filepath.c_str(), "r");
if(fp != NULL)
{
while(!feof(fp))
{
fgets(line, 100, fp);
//cout << line << endl;
if(line[0] == 'a')
{
string str = "";
int i(0);
for(i = 2; line[i] != ' '; i++)
{
if(line[i] != ' ')
{
str += line[i];
}
}
int fi = atoi(str.c_str());
i++;
str = "";
for(int j = i; line[j] != ' '; j++)
{
if(line[j] != ' ')
{
str += line[j];
}
}
int si = atoi(str.c_str());
si--;
fi--;
//cout << "string: " << str << endl;
cout << "fi: " << fi;
//cout << "string: " << str << endl;
cout << " si: " << si << endl;
bs[fi][si]= 1;
}
}
}
fclose(fp);
return bs;
}
The outcome is the following (fi stands for first index and si stands for second index):
sample.gr
fi: 0 si: 1
fi: 0 si: 2
fi: 1 si: 3
fi: 2 si: 4
fi: 3 si: 2
fi: 3 si: 5
fi: 4 si: 1
fi: 4 si: 5
fi: 4 si: 5
000000
000001
011000
001000
000000
000000
The indexes are right, I've checked them, but the matrix should be the following (it is mirrored because of the bitset's right side positioning):
000000
010001
001001
000010
000100
011000
I guess the error is somewhere around the bitset element accessing but I cannot find out what exactly is wrong.
I appreciate any help. Thanks.
With the pointer to a local array problem fixed, your code runs for me and prints what's expected (except mirrored).
But wouldn't it be easier to use C++ I/O in this case?
#include <vector>
#include <bitset>
#include <iterator>
#include <fstream>
#include <sstream>
#include <iostream>
const int N=6;
std::vector<std::bitset<N> > read_graph(const std::string& filepath)
{
std::vector<std::bitset<N> > bs(N);
std::ifstream fp(filepath.c_str());
for(std::string line; getline(fp, line); )
{
if(line.size() > 1 && line[0] == 'a')
{
std::istringstream str(line.substr(1));
int fi, si;
str >> fi >> si;
std::cout << "fi: " << fi << " si: " << si << '\n';
bs[--fi][--si]= 1;
}
}
return bs;
}
int main()
{
std::vector<std::bitset<N> > v = read_graph("sample.gr");
copy(v.rbegin(), v.rend(),
std::ostream_iterator<std::bitset<N> >(std::cout, "\n"));
}
test run: https://ideone.com/z7Had
You are returning a pointer to a local array. Undefined Behavior.
Use a vector<bitset<N> > or similar instead.