I'm new to C++ programming. Whenever I run this, it doesn't print anything.
What I want is to ask the user for their names infinite times and only break after typing "quit". And after typing "quit" it must print all the items in the array. But it's not printing anything. Where am I wrong?
Here's my code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int count = 0;
std::string arr[] = {};
void my_funct()
{
for (int i = 0; i < count; i++){
std::cout << arr[i];
}
}
int main()
{
std::string names;
while (true)
{
std::cout << "Enter your name: \n";
getline(std::cin, names);
if (names == "quit")
{
my_funct();
break;
}
else
{
std::string arr[] = {names};
count++;
}
}
}
arr in my_funct() and arr in if-else statement are two different arrays. You are declaring local version in if-else, which after each iteration of loop is destroyed. You also declared it as an array of zero length - meaning it cannot hold any elements. What you want in your case is std::vector (you even included appropriate header).
You can then resign from count variable and use vec.size() (I've renamed arr to vec) instead.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
std::vector<std::string> vec;
void my_funct()
{
for (int i = 0; i < vec.size(); ++i) {
std::cout << vec[i];
}
}
int main()
{
std::string name;
while (true) {
std::cout << "Enter your name: \n";
getline(std::cin, name);
if (name == "quit") {
my_funct();
break;
}
else {
vec.push_bash(name);
}
}
}
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int count = 0;
vector<string> arr;
void my_funct()
{
for (auto ar : arr) {
std::cout << ar << endl;
}
}
int main()
{
std::string names;
while (true)
{
std::cout << "Enter your name: \n";
getline(std::cin, names);
if (names == "quit")
{
my_funct();
break;
}
arr.push_back(names);
}
}
There is your code I tried to correct. If you need do not understand or need explanation just ask and I'll try to explain
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int counet = 0;
vector<string> arr;
void my_funct()
{
for (int i = 0; i < arr.size(); i++){
cout << arr[i] << endl;
}
}
int main()
{
std::string names;
while (true)
{
std::cout << "Enter your name: \n";
getline(std::cin, names);
if (names == "quit")
{
my_funct();
break;
}
else
{
arr.push_back(names);
}
}
}
Related
Is there any quick way to change a windows wallpaper in C++? I'm trying to animate a wallpaper and am going through a directory of images and setting the wallpaper to an image every few milliseconds, problem is, even when running on a thread, there is sometimes a time gap of a few seconds between wallpaper changes? How do I fix this? Am I doing something wrong? Here's my code:
#include <windows.h>
#include <string>
#include <iostream>
#include <chrono>
#include <thread>
#include <cstdlib>
#include <filesystem>
namespace fs = std::filesystem;
using namespace std;
void thinggg()
{
cout << "Directory(0) or Files(1)?\n";
int choice;
cin >> choice;
int num = 0;
string* images;
if (choice == 1)
{
cout << "How many images?\n";
cin >> num;
cin.ignore();
images = new string[num];
for (int i = 0; i < num; i++)
{
string loc;
cout << i + 1 << ": ";
getline(cin, loc);
images[i] = loc;
}
}
else
{
cin.ignore();
string loc;
cout << "Enter folder location: ";
getline(cin, loc);
// there is probably a much better to do this
for (const auto& entry : fs::directory_iterator(loc))
{
num++;
}
images = new string[num];
num = 0;
for (const auto& entry : fs::directory_iterator(loc))
{
string path = entry.path().string();
if (path.find("png") != string::npos || path.find("jpg") != string::npos || path.find("bmp") != string::npos)
{
images[num] = path;
}
num++;
}
}
int intervals;
cout << "Enter FPS: ";
cin >> intervals;
cin.ignore();
intervals = 1000 / intervals;
int i = 0;
while (true)
{
wstring loc = wstring(images[i].begin(), images[i].end());
const wchar_t* a = loc.c_str();
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (void*)a, SPIF_SENDCHANGE);
i++;
if (i == num) i = 0;
this_thread::sleep_for(chrono::milliseconds(intervals));
}
}
int main()
{
thread t(thinggg);
t.join();
cout << "quit?" << endl;
int a;
cin >> a;
if (a == 1)
{
t.native_handle();
return 0;
}
}
I am taking a string and using stringstream to pull out the ints in the string and then push those into a vector. My problem is doing this when I don't necessarily know the exact number of ints in the string. The string could be "23,45,68" or it could be "-1,10,15,-22,199,12". My code is below:
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
vector<int>v;
char ch;
int a,b,c;
stringstream s(str);
s >> a >> ch >> b >> ch >> c;
v.push_back(a);
v.push_back(b);
v.push_back(c);
return v;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
I realised that the while loop was ending when it hit the "," in the string. In the loop I added code to drop the comma into a char holder "ch" This resolved the problem:
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
//cout << "str is " << str;
vector<int>v;
int x;
char ch;
stringstream num(str);
while (num >> x)
{
num >>ch;
v.push_back(x);
}
return v;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string> using namespace std;
using namespace std;
int main()
{
int spaces = 0;
string input;
cin >> input;
for (int x = 0; x < input.length(); x++) {
if (input.substr(0, x) == " ") {
spaces++;
}
}
cout << spaces << endl;
system("pause");
return 0;
}
I'm trying to make a simple program that counts the number of spaces by adding to an incrementer.
It always returns 0 for some reason.
You have two problems:
cin >> input; should be std::getline(std::cin, input); since std::cin will stop on the first space and not storing the rest of the string.
if (input.substr(0, x) == " ") I could not understand what you meant by this expression. However, what you want is if (input[x] == ' ').
Full Code: (with minor changes)
#include <iostream>
#include <iomanip>
#include <string>
int main(){
unsigned int spaces = 0;
std::string input;
std::getline(std::cin, input);
for (std::size_t x = 0; x < input.length(); x++) {
if (input[x] == ' ') {
spaces++;
}
}
std::cout << spaces << std::endl;
system("pause");
return 0;
}
Online Demo
As #BobTFish mentioed, the right way to do it in real code is:
#include <iostream>
#include <string>
#include <algorithm>
int main(){
std::string input;
std::getline(std::cin, input);
const auto spaces = std::count(input.cbegin(),input.cend(),' ');
std::cout << spaces << std::endl;
system("pause");
return 0;
}
Online Demo
I want to make the vector( mycount) that indicates frequency of the elements in myvec. Can you please let me know what is wrong?
#include <iostream>
#include <vector>
#include <cstdlib>
#include <functional>
#include <algorithm>
using namespace std;
int main() {
int num;
cout << "How many numbers do you want to read in?" << endl;
cin >> num;
vector<int> myvec(num);
std::generate(myvec.begin(), myvec.end(), []()->int {return rand(); });
for (int i = 0; i < num; ++i) {
vector<int> mycount[i] = count(myvec.begin(), myvec.end(), myvec[i]);
cout << mycount[i] << endl;
}
return 0;
}
I suspect you meant to use:
vector<int> myvec(num);
// Create a vector for storing the counts as well.
vector<int> mycount(num);
std::generate(myvec.begin(), myvec.end(), []()->int {return rand(); });
for (int i = 0; i < num; ++i) {
// Get the counts of the element at this index and store it.
mycount[i] = count(myvec.begin(), myvec.end(), myvec[i]);
cout << mycount[i] << endl;
}
your mycount definition is wrong. Check the below code
#include <iostream>
#include <vector>
#include <cstdlib>
#include <functional>
#include <algorithm>
using namespace std;
int main() {
int num;
cout << "How many numbers do you want to read in?" << endl;
cin >> num;
vector<int> myvec(num);
std::generate(myvec.begin(), myvec.end(), []()->int {return rand(); });
vector<int> mycount(num); \\declare mycount with num elements
for (int i = 0; i < num; ++i) {
\\populate the counter for each element
mycount[i] = count(myvec.begin(), myvec.end(), myvec[i]);
cout << mycount[i] << endl;
}
return 0;
}
I was trying to work on a CodeChef problem (Problem Link :: http://www.codechef.com/problems/K2). The code should take in a input for each test case, process, display the result, before moving to the next testcase. But it is just taking inputs without any output.
I am unable to figure out the error as the g++ compiler isn't giving any.
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
using namespace std;
using std::string;
char baseArr[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
bool isPalin(string number)
{
int len=number.size();
bool flag=true;
for(int i=0; i<len/2, flag==true; i++)
{
if(number[i]==number[len-(i+1)])
continue;
else
{
flag=false;
}
}
return flag;
}
string baseChange(long int number, int base)
{
int i=1;
int rem=0;
string output =" ";
while(number>0)
{
rem=number%base;
number=number/base;
output=baseArr[rem]+output;
}
return output;
}
int main()
{
long int input;
int testcase;
string number;
int i;
bool palin=false;
scanf("%d", &testcase);
while(testcase--)
{
palin=false;
scanf("%ld", &input);
for(i=2; palin==false;i++)
{
{
palin=isPalin(baseChange(input, i));
}
}
printf("%d\n",i);
}
}
You assume that the maximum base will be 16, but this may not be the case. You are probably getting a segmentation fault for accessing baseArr beyond valid index. I have not thought of the solution, but I believe the actualy solution can be implemented without considering any character value for the digits.
A solution to the Palindrome problem:
#include <sstream>
#include <cstdlib>
bool test_palindrome(const std::string& value)
{
for (unsigned int i = 0; i < value.length() / 2; i++)
{
if (value[i] != value[value.length() - 1 - i])
return false;
}
return true;
}
std::string find_palindrome(unsigned long num)
{
std::string ret = "";
for (int i = 2; i <= 32; i++)
{
char buffer[100] = {0};
std::string value = ::itoa(num, buffer, i);
std::cout << "Testing: Base=" << i << " Value=" << value << std::endl;
bool test = test_palindrome(value);
if (test)
{
std::stringstream ss;
ss << value << " (base " << i << ")";
ret = ss.str();
break;
}
}
return ret;
}
int main()
{
unsigned long input = 0;
std::cout << "Enter number to search: ";
std::cin >> input;
std::string palin = find_palindrome(input);
std::cout << std::endl << "Palindrome Found: " << palin << std::endl;
return 0;
}