i want to extract number string values of a char array. Actually I want to extract numbers embeded in file names for some file management. For example if there is a file name as file21 then i want the decimal number 21 from this file name.
How can i extract these values?
I tried the following but it results in an unexpected value. I think it is as a result of the implicit typecasting from the char to int while doing the arthimetic operation.
char * fname;
cout<<"enter file name";
cin>>fname;
int filenum=fname[4]%10+fname[5];
cout<<"file number is"<<filenum;
NOTE:
The filenamse are strictly in the format fileXX, XX being numbers between 01 and 99
You need to subtract '0' to get the decimal value of a digit character:
int filenum=(fname[4]-'0')*10+(fname[5]-'0');
Better yet, you should use atoi:
int filenum = atoi(fname+4);
You're getting undefined behavior because you're never allocating memory for the char* you read into:
char * fname = new char[16]; //should be enough for your filename format
or better yet
char fname[16];
Also, what do you expect:
fname[4]%10+fname[5];
to do? Magically concatenate the numbers?
First, you convert the first char to an int, multiply it by 10, convert the second char to an int and add to the first one. A simple google search for char to int would get you there.
How can i extract these values?
There are an infinite number of ways. One way is to use std::istringstream:
#include <string>
#include <sstream>
#include <iostream>
int main () {
std::string fname;
std::cout << "Enter file name: ";
std::getline(std::cin, fname);
int filenum;
std::istringstream stream(fname.substr(4,2));
if(stream >> filenum)
std::cout << "file number is " << filenum << "\n";
else
std::cout << "Merde\n";
}
Here is the simplest code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int filenum;
string fname;
cout<<"enter file name";
cin>>fname;
string str2 = fname.substr(4,2);
istringstream(str2) >> filenum;
cout<<"file number is"<<filenum;
return 0;
}
If your input is that much defined, the simplest solution is scanf:
int main()
{
int theNumber = 0;
scanf("file%d.txt", &theNumber);
printf("your number is %d", theNumber);
}
Check it out in action, reading from char* instead of stdio: http://codepad.org/JFqS70yI
scanf (and sscanf) also throws in checking for proper input format: returns number of fields read successfully. In this case if return value is any other than 1, the input was wrong.
Related
I am trying to reverse the digits of a number. I used strings in it. And I am bound to use strings. Program just give last digit and stop executing. For instance if I put 123 as an input and I only get 3. Instead I should be having 321.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a,b=0;
cin>>a;
string str1="", str="";
for(int i=0;a>0;i++)
{
b=a%10;
str=to_string(b);
a=a/10;
str1=str1+str;
}
cout<<str1.length();
}
Simply change this cout<<str1.length(); to cout<<str1;.
However it's better to use while loop instead of weird for loop.
int main()
{
int a,b=0;
cin>>a;
string str1="", str="";
cout << a << "\n";
while (a>0)
{
b=a%10;
str=to_string(b);
a=a/10;
str1=str1+str;
}
cout<<str1;
}
You're printing the string length rather than string itself.
You are Printing length of string .length() is a builtin function provided by strings. Try running it again by removing .length() keyword from cout command i.e. cout << str1
I'm making a c++ program using string(data type) and char array. Now, the data type is printing words alright. But, I'm having some trouble with the char array. Here's the code:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char str[200];
string str1;
cout<<"Enter a string:\t";
getline(cin,str1);
cout<<str1 <<endl;
cout<<"enter second string:\t";
cin>>str;
cin.get(str,200);
cout<<str;
}
code output
As, you can see in the output, the data type string is printing the words fine. But, the char array is missing the first word. Am I doing something wrong? or does the char array work in different way? Please explain. Thanks.
While you have already discovered that cin >> str; isn't required as you are simply writing again to str with cin.getline (str, sizeof str), there are a number of additional issues you should address:
1. Unless your compiler is ancient, you should #include <string>, not the C-header string.h;
2. Don't use magic-numbers in your code. If you need a constant, e.g. for the maximum number of characters in str, #define a constant or use a global enum to do the same, e.g.
#define MAXC 200 /* if you need a constant, #define one (or more) */
...
char str[MAXC]; /* don't use 'magic-number', use a constant */
That way when, and if you change the number of characters in str in the future, you don't have to pick through your entire code and change every occurrence of the magic-number, e.g. cin.get(str,200);.
3. Validate EVERY user input. Otherwise a failed input can set an error-bit on your input stream and additional attempts to read from a stream with an error-bit set can result in undefined behavior. You could do:
if (!getline(cin,str1)) { /* VALIDATE every input */
cerr << "error: input failure - str1.\n";
return 1;
}
and
if (cin.get (str, sizeof str))
cout << str << endl;
(note: there are no further attempted reads after cin.get (str, sizeof str) so guarding your use of str is sufficient)
4. Always output a newline after your final line output to ensure your program is POSIX compliant. Otherwise on many OS's you will mess up the users prompt if writing to stdout or you will create a non-POSIX compliant output file if redirecting the output to a file, e.g.
my cat has none01:22 wizard:~/dev/src-cpp/tmp/debug>
Putting it altogether, you could do something like:
#include <iostream>
#include <string> /* depending on your compiler */
#define MAXC 200 /* if you need a constant, #define one (or more) */
using namespace std;
int main (void) {
char str[MAXC]; /* don't use 'magic-number', use a constant */
string str1;
cout << "enter a string: ";
if (!getline(cin,str1)) { /* VALIDATE every input */
cerr << "error: input failure - str1.\n";
return 1;
}
cout << str1 << endl;
cout << "enter second string: ";
// cin >> str; /* not needed */
if (cin.get (str, sizeof str))
cout << str << endl;
}
Example Use/Output
$ ./bin/cin.get_getline
enter a string: my dog has fleas
my dog has fleas
enter second string: my cat has none
my cat has none
cout<<"enter second string:\t";
cin>>str;
cin.get(str,200);
here first you are trying to read the second word twice into same variable. comment one of them and try to print the content of str.
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char str[200];
string str1;
cout<<"Enter a string:\t";
getline(cin,str1);
cout<<str1 <<endl;
cout<<"enter second string:\t";
// cin>>str;
cin.get(str,200);
cout<<str<<endl;
}
So, I have a file that contains a pattern of a string then an int alternating line by line.
Something like this:
John McClane
30
James Bond
150
Indiana Jones
50
In this example, I would set John McClane to a string variable and then 30 to an integer variable. My issue is dealing with two types. I want to use getline(), but that only works with strings.
Is there an efficient or "right" way of doing this?
There are a number of approaches you could try.
Get string input, and convert to an integer if valid
Convert every second string to an integer
Try to read an integer when you expect one (just using cin >> in;). If you want a robust program, you can check validity with cin.good()
I don't know if there is a "right" way of doing this per say, but it's not a very taxing operation, so whatever you choose should be fine.
You could make a variable like this
string ibuf;
Then convert it to an integer doing this
getline(cin, ibuf);
(Whatever your int variable is) = strtol(ibuf.c_str(), NULL, 10);
One thing about C++ is that there are a large number of ways to accomplish any one task. One way to get integers from strings is to use a stringstream. There is a tutorial on stringstreams here
As for your problem with reading the alternating file, consider the following pseudocode:
boolean isInt = false;
while(fileIsNotOver) {
//getline
if(isInt) {
//use stringstream to get int here
} else {
//do whatever with the name here
}
isInt = !isInt;
}
I don't know if this fully works as i didn't tested it however it just compiles fine and answer should be something like this i think.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
int counter = 0;
int number;
string test_string;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,test_string) )
{
cout << test_string << '\n';
++counter;
if(counter % 2 == 0 ){
number = atoi(test_string.c_str());
cout << number << '\n';
}else{
cout << test_string << '\n';
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
You can try like this to read a string then an int alternating line by line.
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int main()
{
string name;
int number;
freopen("input.txt", "r", stdin);
while (getline(cin, name))
{
cin >> number;
/*
process the input here
...
...
*/
getline(cin, name); // just to read the new line and/or spaces after the integer
//getchar(); //you can use getchar() instead of getline(cin, name) if there is no spaces after the integer
}
return 0;
}
Thanks !!!
I have an input file which I'm reading in with the basic myFile >> variable since I know the format and the format will always be correct. The file I'm reading in is formatted as instruction <num> <num> and to make >> work, I'm reading everything in as a string. If I have 3 variables, one to take in each piece of the line, how can I then turn string <1> (for example) into int 1? I know the string's first and last characters are brackets which need to be removed, then I could cast to an int, but I'm new to C++ and would like some insight on the best method of doing this (finding and removing the <>, then casting to int)
use stringstream
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string str = "<1>";
int value;
std::stringstream ss(str);
char c;
ss >> c >> value >> c;
std::cout << value;
}
First to get the middle character out you can just do char myChar = inputString.at(1);. Then you can do int myInt = (int)myChar;
Even if you remove the <> characters, your still importing the file content into a string using >> so you still need to cast it to an int. If you have only 1 value, you can follow what Nicholas Callahan wrote in the previous answer, but if you have multiple characters you want to read as int, you dont have a choice but to cast.
You can also resort to sscanf.
#include <cstdio>
#include <iostream>
#include <string>
int main()
{
std::string str = "<1234>";
int value;
sscanf(str.c_str(), "<%d>", &value);
std::cout << value << std::endl;
}
i have a unicode mapping stored in a file.
like this line below with tab delimited.
a 0B85 0 0B85
second column is a unicode character. i want to convert that to 0x0B85 which is to be stored in int variable.
how to do it?
You've asked for C++, so here is the canonical C++ solution using streams:
#include <iostream>
int main()
{
int p;
std::cin >> std::hex >> p;
std::cout << "Got " << p << std::endl;
return 0;
}
You can substitute std::cin for a string-stream if that's required in your case.
You could use strtol, which can parse numbers into longs, which you can then assign to your int. strtol can parse numbers with any radix from 2 to 36 (i.e. any radix that can be represented with alphanumeric charaters).
For example:
#include <cstdlib>
using namespace std;
char *token;
...
// assign data from your file to token
...
char *err; // points to location of error, or final '\0' if no error.
int x = strtol(token, &err, 16); // convert hex string to int