英文:
Counting instances of a character in select lines
问题
Currently learning c++ and I'm pretty stumped. I want to count the instances of a character in a text file - but not including lines that start with a certain character. Specifically, I'm counting instances of Gs and Cs in a text file, but not including lines that begin with "*"
Example:
*metadata information
atgctaatgcaggtcagtcagtcagtcatgcg
atgcagtcagtcactgactgactgactgaata
*metadata information
atgtagcagctagtcagtcagtcagcatatat
gatcgactagctgactgacgtactgactgaat
char Z;
long GC=0;
string Line;
while(getline(InFile, Line))
{
if(Line[0]=='*')
{
InFile.get(Z);
while(InFile.get(Z))
{
if(Z=='G' || Z=='C' || Z=='g' || Z=='c')
{
++GC;
}
}
}
}
I'm able to count the instances of G and C across the entire text, but just haven't been able to limit the function to lines that do not begin with '*'.
英文:
Currently learning c++ and I'm pretty stumped. I want to count the instances of a character in a text file - but not including lines that start with a certain character. Specifically, I'm counting instances of Gs and Cs in a text file, but not including lines that begin with "*"
Example<br/>
*metadata information<br/>
atgctaatgcaggtcagtcagtcagtcatgcg<br/>
atgcagtcagtcactgactgactgactgaata<br/>
*metadata information<br/>
atgtagcagctagtcagtcagtcagcatatat<br/>
gatcgactagctgactgacgtactgactgaat<br/>
char Z;
long GC=0;
string Line;
while(getline(InFile, Line))
{
if(Line[0]=='*')
{
InFile.get(Z);
while(InFile.get(Z))
{
if(Z=='G' || Z=='C' || Z=='g' || Z=='c')
{
++GC;
}
}
}
}
I'm able to count the instances of g and c across the entire text, but just haven't been able to limit the function to lines that do not begin in >
答案1
得分: 2
My understanding of your requirements, you want to ignore lines starting with '*'
.
在上面的代码中,如果第一行字符是'*'
,则忽略该行。
否则,搜索字符串中的'G'
或'C'
字符。
英文:
My understanding of your requirements, you want to ignore lines starting with '*'
.
while (getline(InFile, Line))
{
if (Line[0] == '*')
{
continue; // ignore the line
}
for (int i = 0; i < Line.length(); ++i)
{
const char c = std::toupper(Line[i]);
if ((c == 'G') || (c == 'C`))
{
++GC;
}
}
}
In the above code, if the first line character is '*', the line is ignored.
Otherwise, the string is searched for 'G' or 'C' characters.
答案2
得分: 0
InFile.get(Z);
while (InFile.get(Z))
你不想要这些行。在你的代码中,整个字符串已经被读入string Line;
。
你可能想要
for (auto c : Line) // 遍历Line中的每个字符
{
而且你可能想修正:
if (Line[0] != '*')
因为
但不包括以特定字符开头的行。
英文:
InFile.get(Z);
while(InFile.get(Z))
You don't want those lines. At this point in your code, the whole string has already been read in string Line;
You probably want
for(auto c: Line) // go over every char in Line
{
And you probably want to fix:
if(Line[0] != '*')
because
>but not including lines that start with a certain character.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论