I am taking a course on visual C++ and according to the text, the following code should work (exact copy and paste of the text). Intellisense is saying otherwise, claiming there are 5 errors (informing me that cnt2: undeclared identifier, missing ";" before "{" and missing ";" before "}"). I have never attempted this before with any language (quite honestly didn't know it was a possibility), so any enlightening would be appreciated!
#include <iostream>
// Program 2.: Program demonstrates the for-loop.
int main()
{
using namespace std;
for (int cnt1 = 0, int cnt2 = 9; cnt1 < 10; ++cnt1, --cnt2)
{
cout << cnt1 << "---Hello, World!---" << cnt2 << endl;
}
}
Exact text from my book:
This time there are two counter variables (separated by commas), which are initialized to 0 and 9. Moreover, one is incremented and the other is decremented. Consequently, as shown from the output, one counts forward and one counts backwards. Part 2-the condition-remains the same; that is, it still specifies that we loop ten times.
What am I doing wrong here? Does visual studio 2013 professional not allow this operation? The text said to use Visual C++ to program, I am just more comfortable with VS.
Your code should be like this
// Program 2.: Program demonstrates the for-loop.
#include <iostream>
int main()
{
using namespace std;
for (int cnt1 = 0, cnt2 = 9; cnt1 < 10; ++cnt1, --cnt2)
{
cout << cnt1 << "---Hello, World!---" << cnt2 << endl;
}
}
errors in your version:
1) You cannot include header-files of standard-library in function-scope (and your include was not properly ended, you forgot '>' symbol).
2) When you declare variables in loop type should be pointed only before first.
Related
So, I'm new to C++. I need to learn this language quick for school. But I'm walking against some issues that make it difficult to work with this language. I downloaded visual studio code and followed the steps given by my school. But now I have the problem that sometimes my code just won't print.
Here is an example of a piece of code that does print (btw, I use a "makefile" to run all of this):
#include <iostream>
int main()
{
std::cout << "Hello world!" << std::endl;
return 0;
}
Ofcourse, just a simple "hello world" but still, it does print. Now I'll give an example of a piece of code that won't print:
// C++ program to sort an
// array using bucket sort
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Function to sort arr[] of
// size n using bucket sort
void bucketSort(float arr[], int n)
{
cout << "hello" << endl;
// 1) Create n empty buckets
vector<float> b[n];
// 2) Put array elements
// in different buckets
for (int i = 0; i < n; i++) {
int bi = n * arr[i]; // Index in bucket
b[bi].push_back(arr[i]);
}
// 3) Sort individual buckets
for (int i = 0; i < n; i++)
sort(b[i].begin(), b[i].end());
// 4) Concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < b[i].size(); j++)
arr[index++] = b[i][j];
}
/* Driver program to test above function */
int main()
{
cout << "hello" << endl;
float arr[]
= { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 };
int n = sizeof(arr) / sizeof(arr[0]);
bucketSort(arr, n);
cout << "Sorted array is \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
This is an example of a bucket sort I found online. First, the "n" on the vector<float> b[n] line, gave a red line, I chose the "ignore this error" option. Second, this code won't output anything. If I look into the "debug console" I find this error: ERROR: Unable to start debugging. Unexpected GDB output from command "-exec-run". During startup program exited with code 0xc0000139.
When I looked online I saw some people give the advice to downgrade my gdb version. I want to try that, but I can't find out how to do that haha. Can someone help me get my visual studio code working? This is the most irritating part of programming to me.
ERROR: Unable to start debugging. Unexpected GDB output from command "-exec-run". During startup program exited with code 0xc0000139.
This error means that the program didn't start at all, i.e. died during process setup.
On UNIX this usually happens when the GDB exec-wrapper dies. But I have no idea how VSCode sets up GDB and under what conditions it would die like this.
General advice:
if you want to learn GDB, and you insist on using Windows, then learn GDB in a WSL2 environment.
if you don't want to learn GDB, learn debugging using Visual Studio
you should always learn "native" debugger for the OS you are using -- that way you avoid having to debug various "shims" which (imperfectly) emulate one environment inside another (as appears to be the case here).
I am a c++ beginner and I hope you could help me with some of the fun I am having, you all know what I actually mean.
Here is a snippet of c++ code that I will follow with a brief explanation my problem:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
// this first for loop doesn't affect the execution of the first cout statement.
for (int i = 51; i >= 0; i--) {
srand(time(NULL));
int j = rand();
cout << j << endl;
};
cout << "first cout outside the first for loop" << endl; // executes fine
// this second for loop affects the execution of the following cout statement.
for (int i = 51; i >= 0; i--) {
srand(time(NULL));
int j = rand() % i; //by just adding % i, the next cout statement doesn't execute!
cout << j << endl;
};
cout << "second cout outside the second for loop" << endl; // doesn't execute
}
All right, so, I hope the issue is obvious. To put it in words, why adding the modulus i to the rand() in the second for loop prevents the second cout statement from execution? It took me a whole lot of time to pinpoint what seems to be a big problem in my entire class implementation to this single line. Any feedback/advise/explanation is greatly appreciated.
Cheers.
Programs that execute undefined behavior can have any apparent behavior, including code "in the past" not executing.
You do %0 at the end of your loop. This makes earlier print statements not output. That is acceptable behavior as far as C++ is concerned.
Don't do undefined behavior.
this is my first SO post.
I am very new to programming, and with C++ I thought I might try and make a program that allows the user to submits a block of text (max 500 characters), allows them to enter a 4 letter word and the program return with the amount of times it picks that word up in the text.
I am using X-code and it keeps making a green breakpoint and pausing the program at the 'for' loop function. my code is shown below:
#include <iostream>
#include <string>
#include <math.h>
#define SPACE ' '(char)
using namespace std;
//Submit text (maximum 500 characters) and store in variable
string text;
string textQuery(string msgText) {
do {
cout << msgText << endl;
getline(cin, text); } while (text.size() > 500);
return text;
}
//Query word to search for and store as variable
string word;
string wordQuery(string msgWord) {
cout << msgWord << endl;
cin >> word;
return word;
}
//Using loop, run through the text to identify the word
int counter = 0;
bool debugCheck = false;
int searchWord() {
for (int i = 0; i < text.size(); i++) {
char ch_1 = text.at(i);
char ch_2 = text.at(i + 1);
char ch_3 = text.at(i + 2);
char ch_4 = text.at(i + 3);
cout << i;
if(ch_1 == word.at(0) &&
ch_2 == word.at(1) &&
ch_3 == word.at(2) &&
ch_4 == word.at(3) )
{
counter++;
debugCheck = true;
}
}
return counter;
}
//cout the result
int main() {
string textUserSubmit = textQuery("Please submit text (max 500 characters): ");
string wordUserSubmit = wordQuery("Please select a word to search for: ");
int counterResponse = searchWord();
cout << debugCheck << endl;
cout << "The number of times is: " << counterResponse << endl;
return 0;
}
I get the error at the for loop. Any other advice about how i can make my program work for different words, multiple lengths of words and also how i can highlight the words in text would be helpful.
I really would appreciate if someone could aid me with my problem. Thanks!
I get the error at the for loop.
You should describe the error you get. I happen to have access to Xcode so I can run your code and see what happens, but you should try to spare that of people from whom you want help.
In this case you should describe how the debugger stops the program at the line:
char ch_4 = text.at(i + 3);
includes the message: "Thread 1: signal SIGABRT" and the console output shows
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
Your problem is this: the for loop checks to make sure that i is in the correct range for the string text before using it as an index, but then you also use i+1, i+2, and i+3 as indices without checking that those values are also valid.
Fix that check and the program appears to run fine (given correct input).
Some miscellaneous comments.
Use more consistent indentation. It makes the program easier to read and follow. Here's how I would indent it (using the tool clang-format).
#define SPACE ' '(char) looks like a bad idea, even if you're not using it.
using namespace std; is usually frowned on, though as long as you don't put it in headers it usually won't cause too much trouble. I still could though, and because you probably won't understand the resulting error message you may want to avoid it anyway. If you really don't like writing std:: everywhere then use more limited applications such as using std::string; and using std::cout;.
global variables should be avoided, and you can do so here by simply passing textUserSubmit and wordUserSubmit to searchWord().
there's really no need to make sure text is less than or equal to 500 characters in length. You're using std::string, so it can hold much longer input.
You never check how long word is even though your code requires it to be at least 4 characters long. Fortunately you're using at() to index into it so you don't get undefined behavior, but you should still check. I'd remove the check in textQuery and add one to wordQuery.
The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
(Source: http://codeforces.com/problemset/problem/71/A)
How would you get input from the user given n? I tried using a while loop but it doesn't work:
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int i;
while (i<=n) {
cin>>i ;
i++;
}
}
You probably meant to have something like:
#include <iostream>
int main() {
int n;
cin>>n;
int theInputNumbers[n];
for(int i = 0; i<n; ++i) {
cin >> theInputNumbers[i];
}
}
Your loop is really quite far off of what you need. What you wrote is extremely wrong such that I cannot provide advice other than to learn the basics of loops, variables, and input. The assistance you need is beyond the scope of a simple question/answer, you should consider buying a book and working through it cover to cover. Consider reading Programming Principles and Practice Using C++
Here is a working example of something approximating your question's requirements. I leave file input and output as an exercise up to you. I also make use of C++11's front and back std::string members. You would have to access via array index in older versions.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
int totalWords;
cin >> totalWords;
stringstream finalOutput;
for (int i = 0; i < totalWords; ++i){
string word;
cin >> word;
if (word.length() > 10){
finalOutput << word.front() << (word.length() - 2) << word.back();
}else{
finalOutput << word;
}
finalOutput << endl;
}
cout << endl << "_____________" << endl << "Output:" << endl;
cout << finalOutput.str() << endl;
}
With that said, let me give you some advice:
Name your variables meaningfully. "int i" in a for loop like I have above is a common idiom, the "i" stands for index. But typically you want to avoid using i for anything else. Instead of n, call it totalWords or something similar.
Also, ensure all variables are initialized before accessing them. When you first enter your while loop i has no defined value. This means it could contain anything, and, indeed, your program could do anything as it is undefined behavior.
And as an aside: Why are you reading into an integer i in your example? Why are you then incrementing it? What is the purpose of that? If you read in input from the user, they could type 0, then you increment by 1 setting it to 1... The next iteration maybe they'll type -1 and you'll increment it by 1 and set it to 0... Then they could type in 10001451 and you increment by 1 and set it to 10001452... Do you see the problem with the logic here?
It seems like you are trying to use i as a counter for the total number of iterations. If you are doing this, do not also read input into i from the user. That completely undermines the purpose. Use a separate variable as in my example.
I'm working through a demo program written by someone else, and I'm very confused about some of the statements they are using. I'm not very familiar with C++ (moreso with Obj-C) and I'm not sure if this is valid code or not. Take, for example, the following: (comments are mine)
int main(int argv, char** argc)
{
int perm [20]; //OK, so declare an array of ints, size = 20
for (int i=0; i < 20; i++)
perm = i; //whaaaaa??? thought you need to specify an element to assign to an array...
}
That is one example - my compiler throws an "incompatible types in assignment of 'int' to 'int [20]' error, but apparently others have been able to compile the program. Am I nuts, or is this bad code?
Here's another piece I just don't get:
int d[20] = {0}; //OK, another int array of size 20, initialized to 0's
for (int i = 1; i < n; i++)
{
d = d[i - 1]; //this I don't get - assign the array to one of its own elements??
if (invperm[i - 1] < b)
d++; //this would just increment to the next element?
}
I suspect the error is one of comprehension on my part, as if the code was bad other people would've commented on that fact...if anyone has a good explanation and/or resource I can read to understand this, I would be most appreciative!
Thanks!
*EDITED TO ADD*
In response to the answers below, I did copy/paste that code, and it looks intact to me...I can only assume when the original author posted it, it mangled it somehow. Thanks for the replies, I'm glad I had the right understanding, and I'll try and contact the author to see if there is an un-mangled copy out there somewhere!
All those examples are absolutely wrong. It looks like you lost [i] when you copied the code from wherever you got it from.
I have seen something similar with code sent over messenger programs that treat certain bits of text as emotes and replace them with images that don't get copied as text, but instead get dropped.
Your understanding is fine, that code is just entirely nonsensical.
d++; //this would just increment to the next element?
It would if d were a pointer. However since d is an array, it's simply illegal.
This is most certainly a copy/paste error.
I have succumbed to the temptation of copy/pasting code at one point during a game tech project involving Lua scripts. If the Lua script fails there is no feedback/output that indicates something is failed (which is very frustrating). After debugging for hours I realised my script was using 'smart quotes'.
Whilst this code is broken it can still teach you some things about C++.
int perm [20];
cout << endl << perm << endl;
cout << endl << &perm[0] << endl;
'perm' returns the memory address of the first element of the array. so when you are trying to assign 'i' to 'perm' in that main for loop (20 times) you will know now that you were trying to assign an integer to a memory address, hence the incompatible type error.
The second section however is verry broken and I can't discern much learning from this :P.
I added in an example program to show how pointers/arrays can be used:
#include <iostream>
using namespace std;
int main()
{
int d[20] = {0}; // 20 ints, set to 0
int * ptr = d; // points to d[0]'s memory address
for(int i = 0; i < 20; i++)
{
d[i] = 0 + i; // set array values
}
for(int i = 0; i < 20; i++)
{
// iterates through d and prints each int
cout << endl << "d[i]: " << d[i] << endl;
// dereferences the ptr to get the same int
// then incraments the position of the pointer for next time
cout << endl << "*ptr++: " << *ptr++ << endl;
}
getchar();
return(0);
}