#include <iostream>
using namespace std;
template <class T> class Linear {
private:
T *a;
T key;
int n;
public:
Linear();
void LS();
};
template <class T> Linear<T>::Linear() {
a = new T[10];
cout << "\nEnter the no. of elements in the array";
cin >> n;
cout << "\nEnter the elements in the array";
for (int i = 0; i < n; i++) cin >> a[i];
cout << "\nEnter the key value";
cin >> key;
}
template <class T> void Linear<T>::LS() {
int flag = 0, i;
for (i = 0; i < n; i++) {
if (key == a[i]) {
flag = 1;
break;
}
}
if (flag == 1) cout << "\nElement found at" << i + 1 << "index";
else cout << "\nElement not found";
}
int main() {
Linear<char> l;
l.LS();
return 0;
}
The code is intended to read multiple digits into the array. However when I input
5 23 24 25 26 27
I expect to see
23 24 25 26 27
but I see
2 3 2 4 2
The problem ( thanks to #brc-dd for clarifying ) is that cin behaves counter intuitively with regards to char types. It only reads one character at a time rather than treating char like a number which in all other respects it is. The following code demonstrates this fact
#include <iostream>
#include <stdint.h>
#include <sstream>
using namespace std;
int main(){
std::stringstream ss("27");
int8_t v_int8;
char v_char;
int v_int;
long v_long;
short v_short;
ss >> v_int8;
std::cout << v_int8 << std::endl;
ss.seekg(0);
ss >> v_char;
std::cout << v_char << std::endl;
ss.seekg(0);
ss >> v_int;
std::cout << v_int << std::endl;
ss.seekg(0);
ss >> v_int;
std::cout << v_int << std::endl;
ss.seekg(0);
ss >> v_short;
std::cout << v_short << std::endl;
ss.seekg(0);
ss >> v_long;
std::cout << v_long << std::endl;
ss.seekg(0);
}
the output being
2
2
27
27
27
27
Note that even if you try to get clever and use int8_t it is really only an alias for char and will read character by character rather than as a number like you might assume.
Note: stringstream is like using cin except the input comes from a string instead of user input. ss.seekg(0) just puts the stream back to the beginning of the string.
Related
I want to type this form in my program: s1[k[I]], but it doesn't let me. How can I fix this? Here's my code:
#include <iostream>
using namespace std;
int main(){
int N;
cin>>N;
string s1[N];
for(int k=0;k<N;k++)
{
cin >> s1[k];
}
int counter=0;
for(int k=0;k<N-1;k++)
{
for(int i=0;i<s1[k].size();k++)
{
if(s1[k[i]] == s1[k[i]])
{
cout << s1[k][i] << endl;
}
}
}
return 0;
}
Using the index ([]) operator is generally for arrays. But in this statement: if(s1[k[i]]==s1[k[i]]), k is an int, not an int[]. So how can you index an integer?
Additional: Don't use using namespace std; as it isn't a good practice.
Looks like you tried to join different ideas that don't realy want work together, mixing char arrays and std::strings can be done but is a no good idea because is messy.
As you can see in the example, use the std::string as intended and that's it.
#include <iostream>
int main(){
int N, i;
std::cout << "Add a number -> ";
std::cin >> N;
std::cout << "Add a string -> ";
std::string string;
std::cin >> string;
// recomended method
std::cout << "From std::string -> " << N << " | " << string << std::endl;
char * char_vec = new char [string.length()];
memcpy(char_vec, string.c_str(), sizeof(char) * string.length());
std::cout << "From array -> " << N << " | ";
for(i = 0; i < string.length(); i++){
std::cout << char_vec[i];
}
std::cout << std::endl;
delete [] char_vec;
return 0;
}
So there was this question in recent programming contest.
we have a test case in that question
8
11001101
Now the output I want is 1 but this line
cout << s.erase(0,6) << "\n"
gives 01 even though i want to remove elements from 0 to 6th index position.
How should i remove elements from 0 to 6 (including 6)
Here is the code for reference
#include <vector>
#include <iostream>
using namespace std;
int main(){
int t; cin >> t;
while(t--){
long n; cin >> n;
string s; cin >> s;
int index_l=0;
int index_r=0;
for(int i=0;i<n;i++){
if(s[i]=='1'){
index_l = i;
break;
}
}
for(int i=s.length(); i > index_l;i--){
if(s[i] == '0'){
index_r = i;
break;
}
}/*
cout << s.length() << "\n";
cout << index_l << " " << index_r << "\n";
*/
if(index_r == 0) cout << s << "\n";
else cout << s.replace(index_l,index_r,"0");
}
return 0;
}
Look at some documentation for std::string::erase. There's an overload that takes a starting index and a count of characters to remove. If you want to erase the first 7 characters then you should do:
s.erase(0, 7)
Just to be clear, the second parameter isn't a position. It's the number of characters to remove.
I'd like to show each letter's ascii code
for example
Input: HelloWorld
Ascii Value: 72 + 101 + 108 ... = 1100
And here's my now-code
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char str[32] = { 0 };
int value = 0, i;
cout << "Input: ";
cin >> str;
for (i=0;i<32;i++)
{
value += str[i];
}
cout << "Ascii Value:" << value << endl;
return 0;
}
I only can take the total value of ascii code such as 1100,
not every code value of each letters such as 7 + 11 + ... = 1100.
How can I fix it?
You should use a string for your input (it's c++, not c). Your for loop sums 32 characters, even if the user inputs a shorter string (the programm will read random values from memory). For conversion from int to char you can use stringstream. This results in
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string input;
std::stringstream sstr;
int value = 0;
std::cout << "Input: ";
std::cin >> input;
for (int i = 0; i < input.size(); i++) {
sstr << int(input[i]) << " + ";
value += input[i];
}
std::string str(sstr.str());
std::cout << "Ascii Value:" << str.substr(0, str.size() - 3) << " = " << value << std::endl;
return 0;
}
I'm trying to get all of my outputs to print on one line, at the end of the program. How can I make that happen? Currently, the sum is printed directly after the variables are inputted, looking something like this:
3
100 8
108
15 245
260
1945 54
1999
I want it to look like this:
3
100 8
15 245
1945 54
108 260 1999
This is my code currently:
#include <iostream>
using namespace std;
int main()
{
int pairs = 0;
cin >> pairs;
for (int i=0,num1=0,num2=0; i < pairs; i++)
{
cin >> num1 >> num2;
cout << num1 + num2 << " ";
}
}
At first, it was unclear what you're asking, but I got you. You're doing your input and output in the same loop. You'll need to have an input and an output loop and a container:
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
int main()
{
int pairs = 0;
cin >> pairs;
std::vector<int> sums; // vector to hold sums, your int sum was unused
sums.reserve(pairs);
for(int i = 0; i < pairs; ++i)
{
// better initialize these variables here, otherwise they might
// equal to previous input if this input fails
// (you should declare them in inner-most scope possible anyway)
int num1 = 0, num2 = 0;
cin >> num1 >> num2;
sums.push_back(num1 + num2); // do not cout, append the value to the sums instead
}
for(auto x : sums)
cout << x << " "; // finally print the whole vector
}
Just for the sake of providing a convenient alternative: you can send the output to a std::ostringstream variable until you want to use it...
#include <iostream>
#include <sstream>
int main()
{
int pairs;
if (std::cin >> pairs)
{
std::ostringstream saved_out;
for (int i = 0; i < pairs; ++i)
{
int num1, num2;
if (std::cin >> num1 >> num2)
saved_out << num1 + num2 << " ";
else
{
std::cerr << "ERROR: less inputs than promised\n";
exit(1);
}
}
}
else
{
std::cerr << "unable to parse pairs counter from stdin\n";
exit(1);
}
std::cout << saved_out.str() << '\n';
}
I've also made the input checking a little more robust/verbose.
Just to refresh my concept I'm working on parallel arrays. One is used to store integer data and the other one for char data i.e GPA.
The problem compiles like a charm but the result is not correct, it displays the Student IDs correctly but not the GPA.
The simple cin works fine
I don't really know how to use cin.get and cin.getline using pointers.
In function enter I want to get the two-character-long string (plus one terminating null character).
Code listing:
#include <iostream>
#include <cstring>
using namespace std;
void enter(int *ar, char *arr, int size);
void exit(int *a, char *yo, int size);
int main()
{
const int id = 5;
const char grade = 5;
int *student = new int[id];
char *course = new char[grade];
cout << "\n";
enter(student, course, 5);
exit(student, course, 5);
}
void enter(int *ar, char *arr, int size)
{
for(int i = 0; i < size; i ++)
{
cout << "Student ID: " << i+1 << "\n";
cin >> *(ar+i);
cin.ignore();
cout << "Student Grade: " << i+1 << "\n";
cin.get(arr, 3);
}
}
void exit(int *a, char *yo, int size)
{
for(int i = 0; i < size; i ++)
{
cout << "ID And Grade Of Student #" << i+1 << ":";
cout << *(a+i) << "\t" << *(yo+j) << endl;
}
}
You are attempting to use part of the C++ language, but not embrace it entirely. There is no need for you to manage memory (at all) to solve this problem. Additionally, it would be much better to solve it using the standard language features:
struct Info
{
int StudentId;
std::string Grade; // this could easily be stored as an int or a char as well
};
int main()
{
const std::vector<Info>::size_type SIZE_LIMIT = 5;
std::vector<Info> vec(SIZE_LIMIT);
for (std::vector<Info>::size_type i = 0; i < SIZE_LIMIT; ++i)
{
std::cout << "Enter a Student ID: ";
std::cin >> vec[i].StudentId;
std::cout << "Enter a Grade: ";
std::cin >> vec[i].Grade;
}
std::for_each(vec.begin(), vec.end(), [&](const Info& i)
{
std::cout << "Student ID: " << i.StudentId << ", Grade: " << i.Grade << std::endl;
});
return 0;
}
Which can very easily be converted to account for more than 5 (e.g. virtually infinite) by adding an overload for std::istream& operator>>(std::istream&, Info&) and changing the for-loop to a std::copy operation.
If you absolutely want to keep your hands tied behind your back, you should at least make the following changes:
const unsigned int CLASS_SIZE = 5;
const unsigned int GRADE_SIZE = 5;
int student[CLASS_SIZE];
char course[CLASS_SIZE][GRADE_SIZE] = {};
// initialize course grades to empty strings, if you don't use the = {} above
for (unsigned int i = 0; i < CLASS_SIZE; ++i)
{
memset(course[i], 0, GRADE_SIZE);
}
// ...
// use your constants for your sizes
enter(student, course, CLASS_SIZE);
exit(student, course, CLASS_SIZE);
// ...
// NOTE: you should check to make sure the stream is in a good condition after each input - I leave the error checking code for you to implement
cout << "Student ID: ";
cin >> ar[i];
cout << "Student Grade: ";
cin >> arr[i]; // also note: since you are not using std::string, this can overflow! careful!
// ...
cout << "ID And Grade Of Student #" << i+1 << ":" << a[i] << "\t" << yo[i] << endl;