I have been taking a voluntary computer science course at school share for 1 month and want to practice something. Task:
I am to store a series of numbers with symbols in a string array for the first time. The numbers are to be stored in a two-dimensional int array. But the symbols should look different on output. And the output should be done only using the values of the int array. The numbers are one-digit. There is no need to check if the user makes the input correctly.
This is how the program should look like when it is executed:
Input:
.1.2.3.|.4.5.6.|.7.8.9
-------|-------|-------
Output:
;1;2;3;//;4;5;6;//;7;8;9
=======//=======//=======
I know that you always have to proceed in small steps. I have made it so far that the input is output exactly the same again. I just can't get the solution, I have been sitting here for hours. How do I save the numbers I have saved to the string array to the 2d array? And how do I replace the symbols to look like the example?
My code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int ArrayTwo[3][2] = {0}; //From Task
string ArrayInput[2] = {""}; //From Task
cout << "Input:" << endl;
for (int i = 0; i < 2; i++)
{
cin >> ArrayInput[i];
}
cout << "Output" << endl;
for (int i = 0; i < 2; i++)
{
cout << ArrayInput[i] << endl;
}
system("pause");
return 0;
}
Probably it's simplest to iterate to simply iterate through the input string and convert anything that's a digit to a number:
#include <cctype>
...
void PrintInner(int (&inner)[3])
{
std::cout << ';';
for (auto element : inner)
{
std::cout << element << ';';
}
}
...
int ArrayTwo[3][3];
string ArrayInput[2];
...
auto readPos = ArrayInput[0].cbegin();
for (auto& inner : ArrayTwo)
{
for(auto& element : inner)
{
// skip non-digit chars
while(!std::isdigit(*readPos))
{
++readPos;
}
element = *readPos - '0'; // char codes of digits 0123456789 are next to each other
++readPos;
}
}
cout << "Output" << endl;
PrintInner(ArrayTwo[0]);
for (int i = 1; i != 3; ++i)
{
std::cout << "//";
PrintInner(ArrayTwo[i]);
}
...
Demo on godbolt
In case you're unfamiliar with this: for ( ... : ...) is a ranged for-loop; this sets the loop variable to the elements of the array in increasing order of indices.
Related
I'm currently in the process of learning C++ and for that I'm reading the book "C++ Primer". The book is pretty good so far and I have learned a lot however I experienced weird behaviour using a vector and I'm unsure if this is right or if it's a problem from my side.
The task is:
Read a sequence of words from cin and store the values a vector. After you've read all the words, process the vector and change each word to uppercase. Print the transformed elements, eight words to a line."
This is my code:
#include <iostream>
#include <vector>
using namespace::std;
int main()
{
string input;
vector<string> svec;
while (cin >> input)
{
svec.push_back(input);
for (auto& rows : svec)
{
for (auto& element : rows)
{
element = toupper(element);
}
}
int maxWordsPerLine = 0;
for (auto word : svec)
{
if (maxWordsPerLine >= 8)
{
cout << endl;
cout << word;
maxWordsPerLine = 1;
}
else
{
cout << word;
maxWordsPerLine++;
}
}
}
}
I believe it does the things described in the task but when I type in:
Hello thanks for helping I dont know whats wrong with this problem lol
The output is:
HELLOHELLOTHANKSHELLOTHANKSFORHELLOTHANKSFORHELPINGHELLOTHANKSFORHELPINGIHELLOTHANKSFORHELPINGIDONTHELLOTHANKSFORHELPINGIDONTKNOWHELLOTHANKSFORHELPINGIDONTKNOWWHATSHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGWITHHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGWITHTHISHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGWITHTHISPROBLEMHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGWITHTHISPROBLEMLOL
I hope someone can explain me why this happens and how I can avoid it in the future.
You need to realize there's two steps.
First step: read all the words and convert each to uppercase
Second steps: print all the words
Second step needs to be done after first step is done. However, you have a single while loop. Didn't run it, but simplest change that looks likely to work is:
string input;
vector<string> svec;
while (cin >> input)
{
svec.push_back(input);
for (auto& rows : svec)
{
for (auto& element : rows)
{
element = toupper(element);
}
}
} // extra closing bracket for the while
int maxWordsPerLine = 0;
for (auto word : svec)
{
if (maxWordsPerLine >= 8)
{
cout << endl;
cout << word << " "; // extra space to separate words
maxWordsPerLine = 1;
}
else
{
cout << word;
maxWordsPerLine++;
}
}
For starters you need to include the header <string>
#include <string>
In this while loop
while (cin >> input)
{
svec.push_back(input);
for (auto& rows : svec)
{
for (auto& element : rows)
{
element = toupper(element);
}
}
//...
you are converting all entered words at given iteration to upper case again and again.
And outputting the vector must be removed from the while loop.
So the while loop can look the following way
while ( cin >> input )
{
svec.push_back(input);
for ( auto& element : svec.back() )
{
element = toupper(element);
}
}
After that you may output the vector.
And in this range based for loop
for (auto word : svec)
you should not create a copy of a string stored in the vector. You should declare the variable word as having constant referenced type as
for ( const auto &word : svec)
Also the inner if statement has duplicated code that is not a good style of programming.
if (maxWordsPerLine >= 8)
{
cout << endl;
cout << word;
maxWordsPerLine = 1;
}
else
{
cout << word;
maxWordsPerLine++;
}
Rewrite the if statement within the range based for loop for example the following way
cout << word << ' ';
if ( ++maxWordsPerLine == 8)
{
cout << endl;
maxWordsPerLine = 0;
}
I have an array and I want to subtract each of the elements consecutively, ex: {1,2,3,4,5}, and it will result to -13 which is by 1-2-3-4-5.
But I don't declare or make those numbers fixed as they're taken from the input (user). I only make it like, int array[100] to declare the size.
Then, to get the inputs, I use the for loop and insert them to the array. Let's say first input is 10, then array[0] must be 10 and so on.
The problem is, how do I subtract them? I have two options:
The first element of the array (array[0]) will subtract the next element (array[1]) right after the user input the second element, and the result (let's say it's int x) will subtract the next element (array[2]) after the user input it and so on.
I'll have the user input all the numbers first, then subtract them one by one automatically using a loop (or any idea?) *These elements thing refer to the numbers the user input.
Question: How do you solve this problem?
(This program will let the user input for as much as they want until they type count. Frankly speaking, yeah I know it's quite absurd to see one typing words in the middle of inputting numbers, but in this case, just how can you do it?)
Thanks.
Let's see my code below of how I insert the user input into the array.
string input[100];
int arrayInput[100];
int x = 0;
for (int i = 0; i >= 0; i++) //which this will run until the user input 'count'
{
cout << "Number " << i+1 << ": ";
cin >> input[i];
arrayInput[i] = atoi(input[i].c_str());
...
//code to subtract them, and final answer will be in int x
...
if (input[i] == "count")
{
cout << "Result: " << x << endl;
}
}
You can/should use a dynamic sized container like std::vector as shown below:
#include <iostream>
#include <vector>
int main()
{
int n = 0;
//ask user how many input he/she wants to give
std::cout << "How many elements do you want to enter: ";
std::cin >> n;
std::vector<int> vec(n); //create a vector of size n
int resultOfSubtraction = 0;
//take input from user
for(int i = 0 ; i < n ; ++i)
{
std::cin >> vec.at(i);
if(i != 0)
{
resultOfSubtraction-= vec.at(i);
}
else
{
resultOfSubtraction = vec.at(i);
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
Execute the program here.
If you want a string to end the loop then you can use:
#include <iostream>
#include <vector>
#include <sstream>
int main()
{
std::vector<int> vec;
int resultOfSubtraction = 0, i = 0;
std::string endLoopString = "count";
std::string inputString;
int number = 0;
//take input from user
while((std::getline(std::cin, inputString)) && (inputString!=endLoopString))
{
std::istringstream ss(inputString);
if(ss >> number)
{
vec.push_back(number);
if(i == 0)
{
resultOfSubtraction = number;
}
else
{
resultOfSubtraction-= number;
}
++i;
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
Like for example:
#include <iostream>
using namespace std;
int main()
{
for (int n=10; n>0; n--){
cout<< n <<", ";}
}
This will output the numbers 10,9,8,7,6,5,4,3,2,1
So is there a new way so I just get the last instance of the loop, the 1?
I new at this and google isn't giving me any answers.
There is no direct way to detect whether the current iteration of a for loop is the last one. But if the behavior of the loop is predictable, you can usually write code that can detect when you're on the last iteration.
In this case, you could do something like:
if (n == 1) {
cout << n << "\n";
}
in the body of the loop. (Of course it would be simpler in this case to replace the entire loop with cout << "1\n";, but I presume this is an example of something more complex.)
In more complicated cases, you can save whatever information you need in the body of the loop:
int value_to_print:
for ( ... ) {
value_to_print = i;
}
std::cout << value_to_print << "\n";
On each iteration, value_to_print is replaced by the current value of i. The final value is the value of i on the last iteration.
You could create a variable (outside the loop) to hold the "current" value of n; whatever happens to the loop (exit condition reached, break, an exception is thrown...) the value will stay there:
int last_n;
for (int n=10; n>0; n--) {
last_n = n;
cout<< n <<", ";
if (something) {
break; // works in this case
} else if (something else) {
throw some_random_error; // works in this case too
}
}
cout << "The last value of 'n' was " << last_n << endl;
You can use a simple if statement for that.
int main()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
if( n == 1 ) {
return n;
}
}
}
The simplest way to accomplish this is: -
#include <iostream>
using namespace std;
int main()
{
int x;
for (int n = 10; n > 0; n--){
x = n;
}
cout << x;
return 0;
}
I'm new to programming too and was trying to figure out something which will allow me to get the last instance of my loop as output.
I tried something and got the output, see if it can help you (if there's a mistake please let me know).
Here user input string is being replaced by "*" and instead of giving output of every instance i have made so only last instance is given as output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int string_length;//string length
cout<<"Enter your Email-ID: ";
cin>>str;
string_length = str.length(); //to give the length of input string and use it for the loop
cout<<"lentgh of the string: "<<string_length <<endl;
for(int x = 0; x <= string_length; x++){
str[x] = '*';
while(x==string_length) //string_length is the last instance of the loop
{
cout<<"Here's your Encrypted Email-ID: " <<str<<endl;
break;
}
}
return 0;
}
I have one array containing chars from the input and the other array containing pointers to the corresponding chars in the first array. This part went good.
But then I would like to bubble sort the char** array (array of pointers) so the original array stays untouched but something goes wrong(the text is not sorted).
EDIT: Please discuss only the sorting algorithm
char tab[200];//array of chars
char** t = new char*[tabLength];
//SOMETHING
....
....
int n = tabLength;//length of tab(length of the word it contains)
//TILL HERE EVERYTHING IS FINE -----------------------------------
//bubble sorting below
do{
for(int i = 0; i < n -1; i++){
if(*t[i] > *t[i+1]){
char* x = t[i];
t[i] = t[i+1];
t[i+1] = x;
}
n--;
}
}while(n>1);
cout<<"sorted input";
for(int i = 0; i < tabLength; i++)
cout<<t[i];
cout<<endl;
cout<<"original"<<tab<<endl;
Make sure you print out the values that the pointers point at:
for(int i = 0; i < tabLength; i++)
cout << *t[i];
I would simply use the functionality already at my disposal in the standard library:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string original;
std::getline(std::cin, original);
std::cout << '|' << original << "|\n";
std::string sorted = original;
std::sort(std::begin(sorted), std::end(sorted));
std::cout << "Sorted : " << sorted << '\n';
std::cout << "Original: " << original << '\n';
}
Test run:
|Hello world, how are you doing today?|
Sorted : ,?Haadddeeghilllnoooooorrtuwwyy
Original: Hello world, how are you doing today?
int b;
int array[12];
cout << "Enter binary number: ";
cin >> b;
(for example: b will be 10100)
** How to store b(10100) into an array so that it'll be [1][0][1][0][0] **
cout << array[0] << endl;
** output should be 1 **
cout << array[1] << endl;
** output should be 0 **
Please help thank you.
A string can also be treated as an array of chars. So you can get input into a string, instead, and the cout statements you wrote, should work. However, they will be chars and not ints, so you would be storing '1' and '0' instead of 1 and 0. Converting between them is easy, just use array[0]-'0'
#include <string>
#include <iostream>
using namespace std;
int main()
{
string array;
cout << "Enter binary number: "; cin >> array;
// Suppose the user inputs 10100
cout << array[0] << endl; // outputs '1'
cout << array[1] << endl; // outputs '0'
cout << array[2] << endl; // outputs '1'
return 0;
}
Update: Added compilable code. Note that this is pretty much the original code posted with the question, except for inputting a string.
I had originally wrote up an answer similar to Pablo, but seeing as he already posted it, here is one more consistent with the information given.
It takes an int input and places it into an int array.
#include <iostream>
#include <cmath>
int main( )
{
int b;
int numDigits;
// Get bit string int
std::cin >> b;
// Get the number of digits
numDigits = std::floor( std::log10( ( float )std::abs( b != 0 ? b : 1 ) ) ) + 1;
// Dynamically create a new array of the appropriate size
int* arr = new int[ numDigits ];
// Initialize all the blocks of memory
std::memset( arr, 0, numDigits );
// Fill the array
for( int i = 0; i < numDigits; i++ )
{
arr[ numDigits - i - 1 ] = b % 10;
b /= 10;
}
system( "PAUSE" );
// Delete the array
delete [] arr;
return 0;
}
This one dynamically sets the size of the array so it fits correctly.
The following example stores bits to a raw C-style array as you require. But you can replace it with a std::vector if you want.
int main()
{
// assume sizeof(int) is 32, or you can use heap-allocated array or std::vector
int array[32];
unsigned int mask = 1;
// mask is initially 0x80000000
mask = mask << (sizeof(int)*8 - 1);
int i = 0;
// we start counting from the first "1",
// preceding "0"s are ignored to display
bool started = false;
int b;
cin >> b;
while (mask != 0)
{
// if current bit is "1" or "0"
if (mask & b)
{
started = true;
array[i++] = 1;
}
// if current bit is "0" and counting started
else if (started)
{
array[i++] = 0;
}
// ready to test next bit
mask = mask >> 1;
}
// test result
for (int j = 0; j < i; ++j) cout << array[j];
cout << endl;
return 0;
}
Test cases:
1. b = 8 => array: 1000
2. b = -8 => array: 11111111111111111111111111111000
3. ..
You can use boots dynamic bitset
#include "boost/dynamic_bitset.hpp"
#include <sstream>
#include <iostream>
int main()
{
boost::dynamic_bitset<> val;
std::stringstream input("1010101010");
input >> val; // Input a binary number
// Can use std::cin or another stream
std::cout << val.to_ulong() << "\n";
std::cout << val[5] << "\n";
}
If you don't have boost use the std::bitset.
The only problem with std::bitset it has a fixed size
#include <bitset>
#include <sstream>
#include <iostream>
int main()
{
std::bitset<16> val; // fixed 16 bit size
std::cout << "Enter binary number:\n";
std::cin >> val; // Input a binary number
// Can use std::cin or another stream
std::cout << val.to_ulong() << "\n";
std::cout << val[5] << "\n";
}
STORING A BINARY NUMBER INTO AN ARRAY
char binaryArray [5]; // The array looks like this: [][][][][]
cout << "Enter binary number: ";
cin >> binaryArray; // Stores the binary number into the array: [1][0][1][0][0]
cout << binaryArray[0] << endl; // The first element is sent to standard output.
cout << binaryArray[1] << endl; // The second element is sent to standard output.
For your input the output will be:
1
0
Here we have an array of characters. We input the binary number into the array and then we print each element of the array to display each bit. The first print line accesses the first element [1] [0] [1] [0] [0]. The second print line accesses the second element [1] [0] [1] [0] [0].
Let's say we had a binary number with 100 characters. The way that we output each element of the array would take a long time.
1.) Can you think of a more efficient way of printing out the contents of our array?
2.) How can we ensure that the user is inputting only ones and/or zeroes?