I have a text file like this:
0. ----.----1----.----2----.----3----.----4
1. |Hello1
2. | Hello2
3. | Hello3
4. |Hello4 Hello5
5. | Hello6
6. | Hello7 Hello8
I want to count indentations at the start of the line before any other characters.
This is my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
bool valid;
int index = 0;
int indent = 0;
string line;
ifstream file(argv[1]);
while (getline(file, line))
{
valid = true;
while (true)
{
if (index >= line.length())
{
break;
}
if (valid && line[index] == ' ')
{
indent++;
}
else if (valid && line[index] == '\t')
{
indent += 4;
}
else if (line[index] == 'H') //example for other characters
{
// do something with character
valid = false;
}
index++;
}
cout << indent << endl;
index = 0;
indent = 0;
}
file.close();
return 0;
}
The output:
0
4
8
0
20
8
It works fine now. But I know sometimes the tab character might be 2 or 8 spaces.
How can I know how much space is in one tab character in a text file?
My suggestion is to store the counts of spaces and tabs in separate variables, without attempting to convert tabs to spaces.
It is important to note that tabs and spaces are distinct characters, and this awareness can be advantageous. Tabs might even shown depending on the previous line in some editors
In Python, where indentation is used to define blocks of code, it is imperative to avoid mixing spaces and tabs, even if they appear visually similar in size. Combining spaces and tabs in indentation must result in an error, which says "Inconsistent use of tabs and spaces in indentation."
For example, this code indicates that error.
def nothing():
print("Nothing") # 4 spaces
print("Nothing") # 1 tab
Same for this one.
def nothing():
print("Nothing") # 1 space 1 tab 1 space
print("Nothing") # 1 space 1 tab 1 space