This question already has answers here:
Comma Formatting for numbers in C++
(5 answers)
Closed 8 years ago.
I am trying to make a small program that takes a string and then adds commas to it in three character intervals, like how a currency amount would be formatted. (i.e. 1000 becomes 1,000 and 10000 becomes 10,000).
This is my attempt so far, and it almost works:
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "123456789ab";
int b = a.length();
string pos;
int i;
for (i = b - 3; i >= 0; i-=3) {
if (i > 0) {
pos = "," + a.substr(i,3) + pos;
}
}
cout << pos;
return 0;
}
The output with the sample string is:
,345,678,9ab
It seems it doesn't want to grab the first 1 to 3 characters. What did I do wrong with my code?
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "123456789ab";
int b = a.length();
string pos;
int i;
for (i = b - 3; i > 0; i-=3) {
if (i > 0) {
pos = "," + a.substr(i,3) + pos;
}
}
cout << a.substr(0,i+3)+pos;
return 0;
}
When the index is negative, it means that it can't make any more group of 3. But there may be 1-3 numbers which may be left. We need to explicitly add them
The first character is at index 0. But you never call substr when i is 0, so you can never get that character.
Related
This question already has answers here:
Testing stream.good() or !stream.eof() reads last line twice [duplicate]
(3 answers)
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 24 days ago.
I'm currently working on the "Name That Number" USACO training problem.
It takes a number as input and outputs any matching names found in a dictionary using touch tone telephone keymapping.
The full code consistently gets a bad_alloc thrown on the USACO grader. I've been coding in a replit and it runs fine each time. I've also tried commenting out different parts of the code and running it on the USACO grader but sometimes it runs fine and sometimes it gets a bad_alloc thrown. I think it has something to do with my 2d array of vectors but I'm not sure exactly what or how to fix it.
/*
ID:*****
TASK: namenum
LANG: C++14
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
//function that takes letter and returns associated number
int convert(int letter){ //implicit conversion
if (letter < 81){
letter = letter - 65;
}
else {
letter = letter - 66;
}
int modify = letter % 3;
letter = (letter - modify) / 3 + 2;
return letter;
}
int main() {
ifstream numin ("namenum.in");
ifstream dictin ("dict.txt");
ofstream fout ("namenum.out");
//2d array storing vectors that will store matching names for that index
vector<string> names[8][8]{};
//read names in from dict and store in table
while (dictin.good())
{
string name{};
dictin >> name;
if (name[0] != 'Z' && name[1] != 'Z'){
int i = convert(name[0]) - 2;
int j = convert(name[1]) - 2;
names[i][j].push_back(name);
}
}
//read in digits from input
string digits{};
numin >> digits;
//output matches
int index1 = static_cast<int>(digits[0]) - 50;
int index2 = static_cast<int>(digits[1]) - 50;
string output{};
//check for matches
if (index1 >= 0 && index1 <= 8 && index1 >= 0 && index1 <= 8){
for (int i = 0; i < names[index1][index2].size(); i++){
string matchdigits{};
for (int j = 0; j < names[index1][index2][i].length(); j++){
matchdigits += static_cast<char>(convert(names[index1][index2][i][j]) + 48);
}
if (matchdigits == digits){
output = names[index1][index2][i] + "\n";
}
}
}
if (output == ""){
output = "NONE\n";
}
fout << output;
return 0;
}
This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 3 months ago.
i have been trying to make program that prints random string out of string array. But it is throwing nothing.
I have chaged random number generator algorythm, but it printed same string every time. So i made test aplication and it doesnt work anymore.
Here is my code:
#include <iostream>
using namespace std;
int randomNumber(int min, int max) {
int x = min + rand() % max;
return x;
}
int main() {
string lmao[] = {"xd", "hahaha",",","fjdskl", "fjdskl", "fjkdsljfkdsl","uuruur","fjdksl"};
string lastZ = "";
for (int i = 0; i <= 10; i++) {
int x = sizeof(lmao) / sizeof(int);
int y = randomNumber(0, x);
string z = lmao[y];
if (z == lastZ) {
cout << "Fail";
}
else {
lastZ = z;
cout << "Succes";
}
}
return 0;
}
Don't use rand, use the <random> header.
If you must use rand, seed it with srand before hand.
When I try to compile my code this error pops out:
invalid conversion from 'int' to 'const char*'
My task is to write a program that calculates the sum of numbers with odd index.
Please don't roast me (I'm learning how to code in c++), and give some tips how to fix it and get my code working.
#include <bits/stdc++.h>
#include <cmath>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
cin >> text;
int len = text.length(), sum = 0, number = 0, a = 0;
for (int i = len; i > 0; i++) {
a = text[i];
if (i % 2 == 1) {
number = atoi(a);
sum = sum + number;
}
}
cout << sum;
return 0;
}
Your for loop is incorrect because at the first try it starts at out of range index and increases farther. here :
#include <iostream>
using namespace std;
int main()
{
string text;
cin >> text;
int len = text.length(), sum = 0, number = 0, a = 0;
for (int i = 0; i < len; i++) {
a = text[i];
if (i % 2 == 1) {
number = a - '0';
sum = sum + number;
}
}
cout << sum;
return 0;
}
atoi is a function for converting a string to an integer, but a is a character not a string. That's why you have the error.
Replace atoi(a); with a - '0'. That's a formula for converting a digit character to its integer value.
I see a few issues. The most obvious:
number = atoi(a);
atoi expects a const char *, but a is an int.
Note that it would help if you listed which line produces the error message.
Without trying it, I think you can get rid of the atoi() and just do:
sum += a - '0';
The other choice would be to make a into a string and use text.subst() to just get a single character, then you could do:
sum += atoi (a.c_str());
or
sum += stoi(a);
In programming, there are always a dozen of ways to do the same thing.
Learn to extract functions. This will do your task without converting to string.
int sumOfDigitsInEvenPos(int x, int base = 10) {
x = std::abs(x);
int sum = 0;
while (x) {
sum += x % base;
x /= base * base;
}
return sum;
}
There are more than few mistakes :
starting with declaring 'a' as int.
in Your for loop you are starting with length which should be
length-1.
In for loop again you are using i++ which should be i-- or start with i=0;
When you are getting number why you are taking string as input
taking as int/long should be more convient.
atoi accepts char * not int
try out below code it should solve your problem
#include <bits/stdc++.h>
#include <cmath>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
cin>>text;
int len= text.length();
cout<<len<<endl;
int sum=0,number=0;
char a;
for(int i=len-1;i>0;i--)
{
a=text[i];
if(i%2==1)
{ number= (int)a;
sum = sum+number;
}
}
cout<<sum;
return 0;
}
I think you need to check return code of atoi function, because string consists non only of numeric values.
And length returns size of string, for example 5, but symbols iterates from 0 to 4. text[4] - final symbol.
How to convert string like 3 word 12 with word to a int only contain number 312 without using stoi in C++? My Codeblode gave me an error stoi is not a member of std when I tried to use it.
Thank you in advance!
Go through the line and skip non-digit symbols. And for digits use -'0' conversion and *10 shift approach. E.G.:
#include <stdio.h>
#include <ctype.h>
//or cctype to use isdigit()
#include <string.h>
//or cstring to use strlen()
int main()
{
char str[] = "3 word 12 with word"; // can be any string
int result = 0; // to store resulting number
// begin of solution
for (int i = 0; i < strlen(str); i++)
{
if (isdigit(str[i]))
{
result *= 10;
result += str[i] - int('0');
}
}
// end of solution
printf("%d\n", result);
return 0;
}
Same idea as in VolAnd's answer. Just, because the question is tagged c++, using some STL stuff.
#include <iostream>
#include <numeric>
#include <string>
using namespace std;
int main(){
std::string input("3 word 12 with word");
int num = std::accumulate(input.begin(), input.end(), 0,
[](int val, const char elem) {
if (isdigit(elem)) {
val = val*10 + (elem-'0');
}
return val;
}
);
std::cout << num << std::endl;
return 0;
}
see http://en.cppreference.com/w/cpp/algorithm/accumulate
note: It gets slightly more interesting if you want to allow a leading minus sign....
And using boost::adaptors::filter(rng, pred) on this one would be fun but slightly overdoing it ;-)
Assuming that s is your initial string.
int toInt(string s) {
string digits;
for(size_t i = 0; i < s.size(); i++)
if(s[i] >= '0' && s[i] <= '9')
digits.push_back(s[i]);
int res = 0;
for(size_t i = 0; i < digits.size(); i++)
res = res * 10 + digits[i] - '0';
return res;
}
Leading zeros are not a problem.
Note however that it is possible to receive an overflow if the resulting digits string will contain a big number.
for example, if I want to convert "1234567890" to "1,234,567,890", I can use:
#include <string>
#include <stdio.h>
using namespace std;
int main(){
string st="1234567890";
for(int i=st.length()-3;i>0;st.insert(i,","),i-=3);
printf("%s\n",st.c_str());
return 0;
}
and if I want to convert "1234567890" to "12-3456-7890", just replace the for loop as :
for(int i=st.length()-4;i>0;st.insert(i,"-"),i-=4);
but the problem is, it can apply 1 format method only,and this formatting method is sequential, if I apply 2 for loops together, e.g.:
for(int i=st.length()-3;i>0;st.insert(i,","),i-=3);
for(int i=st.length()-4;i>0;st.insert(i,"-"),i-=4);
the output is 1-,234-,567-,890 but not "1,2-34,56-7,890", what is the generic way to do this?
Or in simpler words, I want a program that can:
1. insert "," for every 3 characters
2. insert "-" for every 4 characters
3. insert ":" for every 7 characters
.
.
.
which can add insert conditions in generic way, what is the simplest way to do this?
Instead of using several loops, you can just use one loop, decremental by 1, with conditional insert. For example:
string st="1234567890";
int originalLength = st.length();
for(int i=originalLength-1;i>0;i--)
{
int positionFromEnd = originalLength - i;
if (positionFromEnd % 3 == 0)
st.insert(i,",");
if (positionFromEnd % 4 == 0)
st.insert(i,"-");
if (positionFromEnd % 5 == 0)
st.insert(i,":");
// add more condition here as need be
}
printf("%s\n", st.c_str());
If it's ok for you, ignore anything that is not a number, in each pass:
#include <string>
#include <stdio.h>
using namespace std;
void insert_delimeter(string& st, string delimeter, int interval) {
for (int i = st.length() - 1, counter = 0; i > 0; i--) {
if (st[i] >= '0' && st[i] <= '9')
++counter;
if (counter == interval) {
st.insert(i,delimeter);
counter = 0;
}
}
}
int main(){
string st = "1234567890";
insert_delimeter(st, ",", 3);
insert_delimeter(st, "-", 4);
printf("%s\n", st.c_str());
return 0;
}
The outcome is
1,2-34,56-7,890
add one more counter to the first for loop
int num=0;
for(int i=st.length()-3;i>0;st.insert(i,","),i-=3)
num++;
for(int i=st.length()-4 + num ;i>0;st.insert(i,"-"),i-=4)
num++;
what happens here is num gets incremented everytime an insert takes place thus it helps to get correct string length in the next string update. which you can use to insert more symbols.