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
Related
#include <iostream>
#include <string>
using namespace std;
static char sentence[100];
void sameletter(char sentence[100])
{
int meter=0;
char letter;
cout<<"Enter the letter you want to find in this sentence : ";
cin>>letter;
for(int i=0; sentence[i] != '\0'; i++)
{
if(sentence[i]==letter)
{
meter++;
}
}
cout<<letter<<" letter used "<<meter<<" time(s)."<<endl;
}
int main()
{
cout<<"Enter Sentence : ";
cin>>sentence[100];
gets(sentence);
sameletter(sentence);
}
This is code i wrote. But for some reason it never includes the first letter to the end result. For example lets say i write "We love stack overflow" and i wanted how many times this sentence has the letter "w" so i hit w and it only shows : "w letter used 1 many time(s)." instead of 2. other letters like "o" works perfectly so it's only a problem about the first letter :/ can someone help me about it ?
Thanks !
This line:
cin >> sentence[100];
will read a single character into the 100th index of sentence, which invokes underfined behavior.
Also, gets has been removed from c++, and you should no longer use it.
Instead, you should use getline:
int main()
{
std::cout<<"Enter Sentence : ";
std::getline(std::cin, sentence);
sameletter(sentence);
}
Also, avoid using namespace std;, it's bad practice.
There's no reason for sentence to be static, or global.
Also, you could just use std::string, instead of char arrays. It will make your life easier. e.g. your loop could be replaced by an algorithm:
int meter = std::count_if(sentence.begin(), sentence.end(),
[=] (unsigned char c) {
return std::tolower(c) == std::tolower(letter);
});
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 want to create a function that takes a string parameter, reverses it and returns the reversed string. There have been some answers, but none work fully.
Here is my code:
#include <iostream>
#include <string>
using namespace std;
string revStr(string word){
string reversed = "";
if(word.size() == 0)
{
return reversed;
}
for (int i = word.length()-1; i>=0; i--){
reversed = reversed+word[i];
}
return reversed;
}
int main(){
string strin;
cout << "enter string;" << endl;
cin>> strin;
cout << revStr(strin);
}
This works only for strings that do not contain a space. When I type in Hello World, it return olleH.
basic_string::operator>>:
2) Behaves as an FormattedInputFunction. After constructing and checking the sentry object, which may skip leading whitespace, first clears str with str.erase(), then reads characters from is and appends them to str as if by str.append(1, c), until one of the following conditions becomes true: [...]
std::isspace(c,is.getloc()) is true for the next character c in is (this whitespace character remains in the input stream).
The method you use by definition reads until a white-space, so you read only Hello into strin. You should use another method for reading like getline or stringstream.
You need to use std::getline to input strings with a space.
For reversing your std::string, consider using std::reverse from <algorithm>, although your algorithm is correct too.
Code:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string strin;
cout << "enter string;" << endl;
getline(cin,strin);
reverse(strin.begin() , strin.end() );
cout << strin;
}
See, cin halts the input at any occurrence of a space or a newline character. So, to input a string with spaces, you'd have to use cin.getline() and that can be done by using the following snippet:
string S;
cin.getline(1000,'\n');
This would take input till the newline character into string S and then we just have to reverse the string, and that can be done in two ways.
Method 1:
Using std::reverse from <algorithm> header file. This function works with all containers and takes iterators as parameters.
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
string S;
getline(cin,S);
reverse(S.begin(), S.end());
return 0;
}
Method 2:
You can create your function which swaps the characters at positions equidistant from end and start, and you get what you need in O(n) time-complexity.
#include <bits/stdc++.h>
using namespace std;
string myfunc(string S)
{
int l = 0;
int r = S.size()-1;
while(l<r)
{
swap(S[l],S[r]);
l++;
r--;
}
return S;
}
int main()
{
ios_base::sync_with_stdio(false);
string S;
getline(cin,S);
S = myfunc(S);
cout<<S;
return 0;
}
What I think is you could do fine with your revStr() but you need to get a whole line input, but using cin considers space as a delimiter, hence you get only Hello out of Hello World.
Replace cin >> strin with getline(cin,strin).
I've been doing programming challenges on coderbyte and while doing one, ran into an issue. I want to isolate a word from a string, do some checks on it and then move to another word. The code I'm going to post is supposed to take only the first word and print it out on the screen. When I run it, it doesn't print anything. I thought that maybe I did something wrong in the while loop so I did a simple test. Let's say my input is "This is a test sentence" and instead of word (in cout), I type word[0]. Then it prints "T" just fine. Can you find what the problem is?
#include <iostream>
#include <string>
using namespace std;
int Letters(string str) {
int i=0;
int len=str.length();
string word;
while(i<len){
if(isspace(str[i])){word[i]='\0'; break;}
word[i]=str[i];
i++;
}
cout<<word;
return 0;
}
int main() {
int test;
string str;
getline(cin, str);
test=Letters(str);
return 0;
}
string word;
is default constructed, which is empty initially. Inside while loop, you tried to do:
word[i] = str[i];
It means you tried to access memory that has not been allocated,resulting in undefined behavior.
Try:
word.append(str[i]);
You can use simpler way to get words from input in C++. It will help you to avoid errors in the future.
#include <iostream>
using namespace std;
int main()
{
string word;
while(cin >> word)
{
// "word" contains one word of input each time loop loops
cout << word << endl;
}
return 0;
}
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.