Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am new to C++ and I am creating a small program. Part of it I have created a way of converting a char array to set of int's. But i was just wondering if there is a better way (more efficient and/or uses better C++ standards). Like for example using atoi on spliced part of the array for each number for etc.
So I start of reading a set of numbers e.g. "11 2 123 44" from a file into a char * array and now want to convert them into there respective values currently doing it as follows:
//char * char_cipher; //{'1', '1', ' ', '2', ... , '4'}
//int length; //length of char_cipher
string s = "";
vector<int> cipher_int;
for (int i = 0; i <= length; i++) {
if (char_cipher[i] == ' ') {
//create num
cipher_int.push_back(stoi(s));
s = ""; //empty num
}
else {
//add to string
s += char_cipher[i];
}
}
Any help would be much appreciated thanks :)
Your code is pretty close. The problem is that you never push the last number in char_cipher onto cipher_int, because there's no space after it. You need to do an extra check after the loop is done.
for (int i = 0; i <= length; i++) {
if (char_cipher[i] == ' ') {
//create num
cipher_int.push_back(stoi(s));
s = ""; //empty num
}
else {
//add to string
s += char_cipher[i];
}
}
if (s != "") {
cipher_int.push(back(stoi(s));
}
Let the STL do the parsing for you. You can use a std::istringstream for that, eg:
#include <string>
#include <sstream>
#include <vector>
std::string str_cipher; //"11 2 123 44"
std::vector<int> cipher_int;
std::istringstream iss(str_cipher);
int num;
while (iss >> num) {
cipher_int.push_back(num);
}
Alternatively:
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
std::string str_cipher; //"11 2 123 44"
std::vector<int> cipher_int;
std::istringstream iss(str_cipher);
std::copy(
std::istream_iterator<int>(iss),
std::istream_iterator<int>(),
std::back_inserter(cipher_int)
);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
Let’s say I have 128 and I broke it up into 1, 2 and 8.
Can anyone give me a logic to build the number again from its broken digits.
If you have a vector of ints, you can do:
#include <vector>
#include <cstdio>
#include <cstdlib>
int to_integer( const std::vector<int>& v ) {
int number = 0;
for ( int value : v ) {
number = 10*number + value;
}
return number;
}
int main() {
std::vector<int> vec {1,2,8};
int number = to_integer( vec );
printf( "Number:%d\n", number );
return 0;
}
If it was a string, you could simply use the C library
#include <cstdlib>
...
const char* str = "128";
int number = ::atoi( str );
But that's likely not what you are asking.
You can do the hands-on approach
#include <cstdio>
int to_integer( const char* str ) {
int number = 0;
for ( ; *str != '\0'; str++ ) {
char ch = *str;
number = 10*number + (ch-'0');
}
return number;
}
int main() {
const char* str = "128";
int number = to_integer( str );
printf( "Number:%d\n", number );
return 0;
}
Please note that this routine above is just a minimal, simplistic and it does not check for cases that the C library does as eg: non-numeric charaters, white spaces, null pointer.
However many times we can guarantee all above as a precondition so the above becomes valid production code. I actually use something like that for high speed trading.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
string sentence;
string output;
string product1;
string product2;
char pr1;
string product;
int i;
getline (cin,sentence);
char pr2;
cin >> pr1;
cin >> pr2;
for (i=0; i < sentence.length();i++){
pr1 = sentence[i]; //asdfg---> g
pr2 = sentence[0]; //--> a
}
output += pr1+sentence+pr2;
cout << output;
return 0;
}
This code is made to swap letters, but for example when I enter asdfg I get gaasdfga. When I enter that, I want to swap g and a. Any idea what I should do? Any idea what's wrong, and how I can improve it?
The below assigns new values to pr1 and pr2. The characters you entered will be lost.
pr1 = sentence[i]; //asdfg---> g
pr2 = sentence[0]; //--> a
To swap the first found of each of the two entered characters, use std::string::find and then std::swap
Example:
#include <utility>
#include <string>
#include <iostream>
int main() {
std::string sentence = "asdfg";
char pr1 = 'g';
char pr2 = 'a';
auto pos1 = sentence.find(pr1);
auto pos2 = sentence.find(pr2);
if(pos1 != sentence.npos && pos2 != sentence.npos) {
std::swap(sentence[pos1], sentence[pos2]);
}
std::cout << sentence << '\n';
}
Output:
gsdfa
An alternative to std::swap(sentence[pos1], sentence[pos2]); would be to do the swap manually:
char temp = sentence[pos1];
sentence[pos1] = sentence[pos2];
sentence[pos2] = temp;
or via a user defined swapper function that you call just like you'd call std::swap:
template<class T>
void swapper(T& lhs, T& rhs) {
// move construct a temporary variable from the argument on the
// left hand side
T temp = std::move(lhs);
// move assign the left hand side from the right hand side
lhs = std::move(rhs);
// move assign the right hand side from the temporary variable
rhs = std::move(temp);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have the following problem and I don't know why and how it's happening.
This is my file:
###########################
###########################
POINTS
68.252 87.2389 -50.1819
68.2592 87.2451 -50.2132
68.2602 87.2436 -50.2133
68.2564 87.2333 -50.1817
68.2618 87.2475 -50.244
68.2476 87.2446 -50.182
68.2582 87.2466 -50.2131
68.2618 87.2475 -50.244
67.9251 87.2509 -49.8313
67.9311 87.2511 -49.8443
67.9786 87.196 -49.8365
67.9735 87.1946 -49.8231
67.9383 87.2513 -49.8574
67.9848 87.1975 -49.8499
68.0704 87.0819 -49.8067
68.0778 87.09 -49.8349
68.0002 87.2009 -49.8769
68.088 87.1 -49.8633
68.1689 86.9755 -49.8051
68.1709 86.9825 -49.8199
68.1672 86.9693 -49.7903
68.2164 86.9204 -49.7972
68.2157 86.913 -49.7821
...
END
##############################
TRIANGLES
...
What I want is to read each line of my file. Split on spaces and convert the string to a float. This is how I am doing it:
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string line;
ifstream inFile;
string path = "C:\\...";
inFile.open(path);
if (!inFile)
{
cerr << "Unable to the open file.";
exit(1);
}
Basic steps to read my file
int vc_size = numOfPoints(inFile); // A function I implemented to get the number of points
vector<float> my_coordinates(vc_size);
int current_pos = 0;
Initializing some variables
while (getline(inFile, line))
{
if (line == "POINTS")
{
while (getline(inFile, line, ' '))
{
if (line == "END" || current_pos >= vc_size)
break;
my_coordinates[current_pos] = atof(line.c_str());
current_pos++;
}
}
}
inFile.close();
for (size_t i = 0; i < vc_size; ++i)
cout << my_coordinates[i] << endl;
return 0;
}
Even though this seem logical, I have a huge problem.
The first value of all my lines (except the first one) disappears (meaning all the 68.something are not in my output).
And what is more confusing is that if I make my vector a vector<string> and do x_coordinates[current_pos] = line; then the code works.
This makes no sens to me because the only step that changes is the conversion from string to float (I tried to convert using stringstream but it's the same incorrect result).
The problem is that your code only accounts for space as a separator for your numbers but in fact you have space and newline as separators.
Change your inner loop to this, so it handles all whitespace
string item;
while (inFile >> item)
{
if (item == "END" || current_pos >= vc_size)
break;
x_coordinates[current_pos] = atof(item.c_str());
current_pos++;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I am supposed to write a program that takes in string like "pre#ogrann##mmink#g" and returns "programming", it is like your backspace button is broken and when you hit it you get '#' instead of erasing the char out, and I have to fix it. I have working code here under but it is way to slow, and I might have to deal with huge string, any suggestion how I could do it better/faster?
#include <string>
#include <iostream>
using namespace std;
int main() {
string str;
while(cin >> str) {
bool done = false;
while(!done) {
if((int)str.find('#')>-1) {
str.erase(str.find('#')-1, 2);
} else {
done = true;
}
}
cout << str << endl;
}
}
Here's how I would do it. I haven't tested it to see if it is actually faster, but as it has a complexity of O(N), I think it should be fast enough:
while (std::cin >> input) {
std::string result;
result.reserve(input.length());
for (auto ch : input) {
if (ch == '#') {
if (result.length() > 0)
result.pop_back();
continue;
}
result += ch;
}
std::cout << result << '\n';
}
#include <iostream>
#include <string>
using namespace std;
string s = "pre#ogrann##mmink#g";
int main() {
string out;
int len = s.length();
for (int i = 0; i < len; i++) {
if(s[i] == '#') {
s.erase(i-1,2);
len = s.length();
i -= 2;
}
}
cout << s;
return 0;
}
This produces a working output.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this function:
void map()
{
map<char, string> change;
string usrstr = "A APPLE AND BANANA";
change['A'] = "00011";
change['B'] = "11001";
change['C'] = "01110";
change[' '] = "$$";
}
How would I go about changing all occurrences of 'A' in my string to "00011" and the same for B, C and space. All help is much appreciated
P.S The string wont always be the same
Not sure to understand: how about:
std::string str = "A APPLE AND BANANA";
std::replace(str.begin(), str.end(), "A", "00011" );
std::replace(str.begin(), str.end(), "B", "11001" );
...
You can and should probably use string::replace.
Even with your most recent comment.
But this might have been what you were trying to do:
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <string>
using namespace std;
int main()
{
char temp;
map<char, char*> change;
string lol = "A APPLE AND BANANA";
change['A'] = "00011";
change['B'] = "11001";
change['C'] = "01110";
change[' '] = "$$";
for (int i = 0; i < lol.length(); i++)
{
temp = lol[i];
if (change[temp])
cout << change[temp];
else
cout << lol[i];
}
cout << endl;
cin.get();
return 0;
}