I need to fill this array via user prompt. I was thinking to read in the user entry to a string and then assign that string to the array but that doesn't seem to be the right way to approach this. Could someone help me out?
The error I'm receiving reads "array type array[100] is not assignable"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string.h>
using namespace std;
int main()
{
string theString;
char array[100]; // ARRAY MAX SIZE
int length = sizeof(array)-1;
char * ptrHead = array;
char *ptrTail = array + length - 1;
//USER PROMPTS & ARRAY FILL
cout << "Please enter a string to be reverse: " << endl;
cin >> theString;
array= theString;
//WHILE LOOP SWAPPING CHARACTERS OF STRING
while (ptrHead < ptrTail)
{
char temp = *ptrHead;
*ptrHead = *ptrTail;
*ptrTail = temp;
ptrHead++;
ptrTail--;
}
cout << array << endl;
return 0;
}
arrays are not assignable. You should use strcpy here:
But for this you'll have to convert theString to C like string.
strcpy(array, theString.c_str() );
Then adjust your ptrTail pointer too , like following :
int length = theString.size();
char *ptrTail = array + length - 1;
See Here
cin >> array; should put the input directly into the array, which I'm guessing is what you want
Also, there's a problem in your string reversal logic. You are reversing the entire array, not just the part that has been filled, which will put the filled portion at the end of the array. Consider using a function like strlen() to find out how long the actual input is.
You can copy the string to the array with strcpy or input the data directly to the array with cin >> array, but the better solution would be just not to use a char array, just use the string in your algorithm. That is also a better solution because you can overflow a fixed size char array
cout << "Please enter a string to be reverse: " << endl;
cin >> theString;
for (unsigned int i = 0; i <= theString.size() / 2; ++i)
swap(theString[i], theString[theString.size() - 1 - i);
cout << theString<< endl;
Edit
The same using pointers:
std::cout << "Please enter a string to be reverse: " << std::endl;
std::cin >> theString;
char* i = &theString[0];
char* j = &theString[theString.size() - 1];
for (; i < j; ++i, --j)
std::swap(*i, *j);
std::cout << theString << std::endl;
Related
I am trying to convert an input character array, to an int array in c++.
Inputs would be in a format like: 'M 911843 6', where the first value of the char array is a uppercase letter, which I convert to an ASCII value and -55.
Edit: I should also mention I just want to use the iostream library
The last value of the char array can be a letter or number also.
I want to retain the exact number value of any input in the char array, which is why I convert to an ASCII value and -48, which retains the same number, but stored as an int value:
I use the checkdigit() function to check if the char input is a number or not.
The difficulty I am facing is that the input will always have a blank space at i[1] and i[8] (if we count i[0] as the first value) - so I try to give them an int value of 0 (int of a " " is 0)
Upon several debugging attempts, I found that it is after the blank space is given a 0 value, the output in my for loop keeps outputting the wrong values, I suspect it has something to do with the isdigit() function in my for loop.
If the spaces from M 911843 6 were removed, the int output is usually fine, e.g. a char input of
M9118436 will return an int array of [22][9][1][1][8][4][3][6].
The output with spaces: [22][0][-183][-120][37][-118][-59][72][0][-55]
Ideal output: [22][0][9][1][1][8][4][3][0][6]
The code is listed below, any help or advice would be greatly appreciated, thanks!!
#include <iostream>
using namespace std;
int main() {
char a[10];
int z[10];
int i = 0;
int r; //result of the isdigit check (0 or 1)
cout << "in ";
cin >> a;
for (int i = 0; i < 10; i++) {
r = isdigit(a[i]);
if (r == 0) {
if (i==1 || i==8)
z[i] = 0;
else z[i] = int(a[i]) - 55;
}
else {
z[i] = int(a[i]) - 48;
}
}
cout << z[0] << "\n" << z[1] << "\n"<< z[2]<< "\n" << z[3] << "\n"<< z[4] << "\n"<< z[5] << "\n"<< z[6] << "\n"<< z[7]<< "\n" << z[8] << "\n"<< z[9];
return 0;
}
The problem is that cin >> a; does not read sizeof(a) characters, but up to the first space character and will terminate that with a null.
That means that you array will containt 'M', '\0' and 8 uninitialized characters. You must read the characters one at a time with unformatted reads:
for (auto& c : a) {
cin.get(c);
if (!cin) {
cerr << "Incorrect input\n";
return EXIT_FAILURE;
}
}
Just a follow on from Serge's answer which gave me a good understanding of how strings are read - I solved my problem using cin.getline() function.
Unable to get the index from the second array to match the first array
// array constants
const int people = 7;
const int phoneNumbers = 7;
int main() {
char person, family;
int index;
string found;
int size =7;
//array declaration and set values
string people [] ={"Darryl","Jasmine","Brian","Duane","Ayana","Mia","Maya"};
// const char phoneNumbers = 7;
string phoneNumbers[] = {"678-281-7649", "818-933-1158", "212-898-2022",
"361-345-3782","817-399-3750","313-589-0460","818-634-4660"};
//set boolean value
found = "False";
//initialize index
index = 0;
// search variable and user input
cout << "who are you looking for? " << endl;
cin >> people[index];
for (index=0; index<=6; index--) {
if (people[index] == people[index] )
cout << "phone num for " << people[index] << " is "<<
phoneNumbers[index] << endl;
}
return 0;
}
When I put in Jasmine which is the people[] array, the phoneNumbers[] array brings back the first index of phoneNumbers[] which it should bring back the second index on phoneNumbers[] array
There are two problems here.
You are replacing content of the people[0] with the cin - so first item of the array will be always user's input.
You are decrement index, so the FOR cycle goes to the indexes 0,-1,-2... This is problem as arrays in C and C++ goes from 0 to upper values.
I would prefer to add one variable:
string input;
then:
cin >> input;
for cycle should be used:
for (index = 0; index < 6; index++)
and in your condition I would use:
if (person[index] == input) ...
A much cleaner way of doing this would be too use std::map provided by the C++ standard template library. Below is my take on what you're trying to achieve:
// phoneNumber.cpp
#include <iostream>
#include <map>
int main()
{
// delcare a map variable that maps people's names to phone numbers
std::map <std::string,std::string> lookUpPhoneNumber = {
{"Darryl", "678-281-7649"},
{"Jasmine", "818-933-1158"},
{"Brian", "212-898-2022"},
{"Duane", "361-345-3782"},
{"Ayana", "817-399-3750"},
{"Mia", "313-589-0460"},
{"Maya", "818-634-4660"}
};
// take input name
std::string inputName;
// user prompt
std::cout << "who are you looking for?: ";
std::cin >> inputName;
// look up name in map
if(lookUpPhoneNumber.find(inputName) != lookUpPhoneNumber.end()){
std::cout << "Phone num for " << inputName << " is: " << lookUpPhoneNumber[inputName] << "\n";
} else{
std::cout << "Name does not exist!\n";
}
return 0;
}
To compile and run, use the following command:
g++ -std=c++11 -o phoneNumber phoneNumber.cpp
./phoneNumber
Or check your compiler option to enable compiling with c++11 standard or higher.
well I'm trying to get the user to input an integers as much as they want, until they input a negative number. 1st step was to use the ATOF function to convert string to number(which I did), and then allow the user to input integers(I only manage to do once just to see if I can use the atof function correctly.
Any help/tips is appreciated on giving me the right direction.
Here is my code thus far:
#include <iostream>
#include <string>
int main() {
using namespace std;
char buffer[256];
char tempBuff[256] = {'\n'};
double result;
int count = 0;
cout << "Testing " << endl;
cout << "Enter Any integers: ";
cin.getline(buffer,256);
for(int i = 0; i < strlen(buffer); i++)
{
if(isdigit(buffer[i]))
{
tempBuff[count] = buffer[i];
count++;
}
}
if (atof(tempBuff) > 0) {
result = atof(tempBuff) / 2;
}
cout << endl << "The integer you put was: " << tempBuff
<< " And dividing the integers "<< result << endl;
cin.ignore();
return 0;
}
How is atof supposed to know how many valid digits tempBuff contains? The atof function only accepts a C-style string as its input. Otherwise, it has no way to know how many characters are valid.
You can use tempBuff[count] = 0; before the call of atof. A C-style string is terminated by a zero byte.
there's a problem facing me in this question :
"write a c++ console program to accept five
integers values from keyboard in one line separated by spaces . the program then stores the five values in an array using pointer . then print the elements of the array on the screen ."
I tried to make a string variable and accept 5 integers from user then convert it to integer but it doesn't work well because it doesn't take numbers after space .
any help guys ??
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
string numbers;
getline(cin, numbers);
int arr[5];
int *ptr;
int values;
stringstream convert(numbers);
convert >> values;
cout << values;
}
It will only take one at a time, you need to add more calls to convert like so:
stringstream convert(numbers);
convert >> values;
cout << values;
convert >> values;
cout << " " << values;
convert >> values;
cout << " " << values;
The C++faq has a good section on this.
Without major modification, if you need to put the number directly into the array using a pointer, you can do this:
int *ptr = arr ;
convert >> *ptr++ ;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
for( unsigned int i = 0; i < 5; ++i )
{
cout << arr[i] << " " ;
}
cout << std::endl ;
I successfully made it
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
int arr[5];
string number;
cout << "Please enter 5 integers separeted with spaces " << endl;
getline(cin, number);
int *ptr = arr ;
stringstream convert(number);
convert >> *ptr++ ;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
for( int i = 0; i < 5; ++i )
{
cout << arr[i] << " " ;
}
cout << std::endl ;
}
I the numbers variable is string you can search for first non space character using numbers.find_first_not_of(" "); and first space character by numbers.find_first_of(" "); then create a subset using substr(.....) now place the substr in another string variable. Now convert the substring to int. repeat the steps for number of times you need. i.e. place the whole code inside a while loop. Terminate the loop whenever numbers.find_first_of(" ");returns numbers.end()
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?